Error Handling: try / except / finally / else
Errors are normal in programming. Files don't exist, network requests fail, users enter invalid input. Python's exception system lets you handle these situations gracefully instead of crashing.
Basic try / except
Code in the try block runs until either it completes or an exception is raised. If an exception matches an except clause, that clause runs. If no except matches, the exception propagates up.
Catching Specific Exceptions
Always catch the most specific exception you can:
except as e โ Accessing the Exception Object
The exception object e gives you access to the error message and any exception-specific attributes.
Multiple except Clauses
You can also catch multiple exceptions in one clause:
The else Clause
The else block runs only if the try block completed without raising an exception. It's ideal for code that should run on success but that you don't want inside the try block:
The finally Clause
The finally block always runs, whether an exception occurred or not. Use it for cleanup:
finally runs even if:
- The
tryblock raises an unhandled exception - The
exceptblock raises a new exception - A
returnorbreakstatement is executed
Complete Structure
All four clauses together:
Exception Hierarchy
Python exceptions form a hierarchy. Catching a parent class catches all subclasses:
Common Exceptions Quick Reference
| Exception | When it occurs |
|---|---|
ValueError | Correct type, wrong value: int("abc") |
TypeError | Wrong type: 1 + "2" |
KeyError | Missing dict key: d["missing"] |
IndexError | List index out of range: lst[100] |
AttributeError | Attribute doesn't exist: obj.missing |
FileNotFoundError | File doesn't exist |
ZeroDivisionError | Division by zero |
NameError | Variable not defined |
StopIteration | Iterator exhausted |
RuntimeError | Generic runtime error |
Best Practices
Do: Catch specific exceptions. Handle errors at the appropriate level. Use else for success-path code. Use finally for cleanup (though context managers are often better).
Don't: Use bare except: (catches even KeyboardInterrupt). Silently swallow exceptions (except: pass). Catch Exception unless you re-raise or log it.
Knowledge Check
When does the `else` clause in a try/except run?
What is the key difference between catching `Exception` vs bare `except:`?
When does the `finally` block run?