Error Handling with Try and Except
Master robust error handling in Python using try, except, else, and finally blocks, understanding common exception types, and avoiding the bare except anti-pattern.
Imagine driving a modern car. If you suddenly lose traction on a patch of black ice, the car does not self-destruct or explode; an onboard computer activates the Anti-Lock Braking System (ABS) and traction control, stabilizes the vehicle, and lets you continue driving safely.
In computer programming, unexpected events are guaranteed to happen:
- A user types
"twenty"into an input box expecting a numerical age. - Your internet router momentarily disconnects while downloading an image.
- A user asks to open a spreadsheet file that was deleted five seconds ago.
Without error handling, any of these events causes Python to panic, halt execution immediately, spit out an intimidating red traceback, and crash your entire application.
With Exception Handling, your code anticipates potential failure points, catches errors gracefully, takes corrective action, and keeps running seamlessly.
1. The Core Pattern: try and except
To protect against crashes, place code that might fail inside a try block, and define your recovery plan inside an except block:
raw_input = "forty-two"
try:
# Risky operation: converting string to int
age = int(raw_input)
print(f"Your age is {age}.")
except ValueError:
# Recovery plan: executes ONLY if int() raises ValueError
print("Error: Please enter numbers only (e.g. 42), not written words.")
print("Application continues running smoothly!")
Output:
Error: Please enter numbers only (e.g. 42), not written words.
Application continues running smoothly!
If raw_input was "42", Python would run the try block, print "Your age is 42.", and skip the except block completely.
2. Common Python Exceptions You Must Know
Python has built-in names for different categories of failure. Knowing them allows you to catch the right error:
| Exception Type | When it happens | Example |
|---|---|---|
ValueError | Correct type, but invalid value | int("abc") |
TypeError | Operation applied to wrong data type | "Score: " + 10 |
ZeroDivisionError | Dividing any number by zero | 100 / 0 |
IndexError | List index out of bounds | [1, 2][99] |
KeyError | Non-existent dictionary key | {"a": 1}["b"] |
FileNotFoundError | File does not exist on disk | open("missing.txt") |
3. Handling Multiple Specific Errors
A single block of code might encounter multiple distinct problems. You can attach multiple except blocks to handle each scenario individually:
def divide_inventory(total_items, num_boxes):
try:
items = int(total_items)
boxes = int(num_boxes)
per_box = items / boxes
return per_box
except ValueError:
print("Invalid input: Please provide integer numbers.")
except ZeroDivisionError:
print("Invalid packing: You cannot pack items into 0 boxes!")
# Test different error scenarios:
divide_inventory("100", "abc") # Triggers ValueError
divide_inventory("100", "0") # Triggers ZeroDivisionError
print("Valid result:", divide_inventory("100", "4")) # 25.0
Inspecting Error Messages with as error
To capture the actual error message generated by Python, use the as keyword:
try:
with open("non_existent_file.csv") as f:
data = f.read()
except FileNotFoundError as err:
print(f"File lookup failed! System details: {err}")
Output:
File lookup failed! System details: [Errno 2] No such file or directory: 'non_existent_file.csv'
4. The Complete Four-Part Suite: try, except, else, finally
Python provides the most expressive error handling architecture in modern programming with four interconnected clauses:
def process_user_data(user_input):
try:
# 1. RISKY: Attempt the operation
score = int(user_input)
except ValueError as err:
# 2. FAILURE: Runs ONLY if an exception occurred in 'try'
print(f"Conversion failed: {err}")
else:
# 3. SUCCESS: Runs ONLY if 'try' succeeded without ANY errors!
print(f"Success: Validated score {score} points.")
# Perform further calculations cleanly separated from try
finally:
# 4. CLEANUP: Runs NO MATTER WHAT (success or failure!)
print("Audit: Session check completed.\n")
process_user_data("95") # Runs: try -> else -> finally
process_user_data("invalid") # Runs: try -> except -> finally
Output:
Success: Validated score 95 points.
Audit: Session check completed.
Conversion failed: invalid literal for int() with base 10: 'invalid'
Audit: Session check completed.
Why Use else?
Placing non-risky code in the else block prevents you from accidentally catching errors in subsequent logic that you did not intend to handle!
Why Use finally?
The finally block is guaranteed to run even if an unhandled exception or an explicit return occurs inside the try block. It is the premier tool for cleanup tasks: closing database connections, releasing locks, and shutting down network sockets.
5. The Cardinal Sin: The Bare except: Anti-Pattern
Here is the single most dangerous mistake a Python developer can make:
# NEVER, UNDER ANY CIRCUMSTANCE, WRITE THIS:
try:
risky_code()
except: # BARE EXCEPT!
pass
Why is this catastrophic?
- It traps
KeyboardInterrupt: When you press Ctrl + C in your terminal to stop a rogue script, Python raisesKeyboardInterrupt. A bareexcept:intercepts it and refuses to shut down! - It hides typos: If you typed
prinnt("Hello")instead ofprint("Hello"), Python raises aNameError. The bare except swallows the error silently, leaving you wondering why your code isn’t working!
[!CAUTION] Always specify the exact exception you intend to handle (
except ValueError:). If you truly need a general catch-all for unexpected application errors, useexcept Exception as err:so system exits and keyboard interrupts can still terminate your process.
Summary & What’s Next
- Enclose risky operations inside
try:blocks. - Catch specific errors with
except SpecificError as err:. - Use
else:for code that should only execute when no exceptions occurred. - Use
finally:for guaranteed cleanup logic that must always run. - Never write bare
except:statements.
What if Python’s built-in exceptions don’t accurately describe your application’s domain logic (like an InsufficientFundsError)? Learn how to craft your own errors in custom-exceptions.