Exception Handling in Python: Try, Except, Finally
Learn how to use Python Exception Handling (Try/Except) to prevent your Artificial Intelligence scripts from crashing when encountering messy data.
Introduction
In a perfect world, your data is always perfectly formatted and your servers are always online. In reality, data science is messy. Values are missing, APIs timeout, and users input strings instead of integers. When these inevitable errors occur, Python naturally panics and completely crashes the program. To prevent this, we use Exception Handling.
What You Will Learn
- What an Exception is.
- How to use the
try,except,else, andfinallyblocks. - How to handle specific types of errors (e.g.,
ValueError,ZeroDivisionError). - Why exception handling is mandatory for long-running AI training jobs.
Why This Topic Matters
Imagine training a Deep Learning model on a supercomputer for 3 days. On day 3, it encounters a single corrupt image file in the dataset. If you did not write an exception handler, Python will crash, and your 3 days of expensive training will be permanently lost. Exception handling allows the code to log the error, skip the bad file, and keep training.
Prerequisites
Detailed Explanation & Examples
An "Exception" is an event that disrupts the normal flow of the program.
We handle these events using a try...except block.
try: Lets you test a block of code for errors.except: Lets you handle the error without crashing.
1. Basic Try/Except
# Without try/except, this would crash the whole program with a ValueError
raw_data = "Missing"
try:
# Attempting to convert the word "Missing" into an integer
clean_data = int(raw_data)
print("Success:", clean_data)
except:
print("WARNING: Data corruption detected. Could not convert to Integer.")
clean_data = 0 # Assign a default safe value
print("Program continues running safely...")
2. Catching Specific Exceptions
It is dangerous to use a bare except: because it catches every error, even ones you didn't anticipate. It is best practice to catch specific errors.
def process_data(value, divisor):
try:
result = int(value) / divisor
print("Result:", result)
except ValueError:
print("Error: The value provided is not a number.")
except ZeroDivisionError:
print("Error: Cannot divide by zero in mathematics.")
except Exception as e:
# Catches any other error and prints the system error message
print(f"An unexpected error occurred: {e}")
process_data("10", 0) # Triggers ZeroDivisionError
process_data("Hello", 2) # Triggers ValueError
3. The finally Block
The finally block will execute regardless of whether the try block succeeded or failed. It is almost always used to clean up resources, like closing a database connection or saving a model checkpoint.
try:
print("Opening database connection to fetch training data...")
# Simulate an error
x = 1 / 0
except ZeroDivisionError:
print("Error during data fetch!")
finally:
print("Closing database connection. (This always runs!)")
Visual Diagram (Mermaid)
graph TD
A[Start Try Block] --> B{Does Error Occur?}
B -- Yes --> C[Jump to Except Block]
C --> D[Handle Error / Print Warning]
B -- No --> E[Execute Else Block optional]
D --> F[Execute Finally Block]
E --> F
style C fill:#EF4444,stroke:#fff,color:#fff
style F fill:#8B5CF6,stroke:#fff,color:#fff
Industry Use Cases
- Web Scraping for NLP: When scraping 10,000 websites, some sites will inevitably be offline or block you.
try/exceptensures the scraper logs the failed URL and moves to the next one, rather than crashing on the 5th site. - Model Checkpointing: Using
try/except/finallyin a training loop. If a power outage or GPU failure crashes the script, thefinallyblock can trigger a command to save the model's current weights to the hard drive before the script dies.
Advantages
- Resilience: Creates robust pipelines that can run continuously for days or weeks.
- Debugging: Explicitly catching
Exception as eallows you to log the exact error to a file while keeping the program running, making debugging much easier later.
Best Practices
- Log errors, don't ignore them: Do not write
except: pass(which silently ignores the error). If data is failing to process, you need to log it so you can investigate why. - Be Specific: Catch the exact error you expect (e.g.,
FileNotFoundError) rather than a generalException.
Common Mistakes
- Catching everything indiscriminately: As mentioned,
except:without specifying the error type is considered a bad practice in professional engineering (known as "swallowing the exception").
Summary
Data is imperfect. Hardware fails. APIs go offline. Exception Handling (try, except, finally) is the safety net that prevents these inevitable issues from permanently crashing your Python applications and ruining long-running Artificial Intelligence tasks.
Next Topic
Now that we can safely handle errors, it's time to actually read the data we want to process. Move on to: File Handling.