Try, Except, and Finally
Catch exceptions like ZeroDivisionError and ValueError, execute cleanup code in finally.
Learning objectives
- Prevent application crashes with try/except blocks
- Catch specific exception types rather than bare excepts
- Use else for success paths and finally for guaranteed execution
Lesson material
Handling Exceptions
Errors in Python cause exceptions. Using try/except prevents program termination.
Example code
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Division by zero is not allowed"
else:
return f"Result: {result}"
finally:
pass # Always runs
print(safe_divide(10, 2))
print(safe_divide(10, 0))
Practice exercise: Safe Integer Parsing
Write a function `parse_int(val)` that converts `val` to int and returns it. If ValueError occurs, return `-1`. Print `parse_int("123")` and `parse_int("abc")`.
Test yourself with the Module 7: Error & Exception Handling quiz →