How do I use try/except/else/finally for error handling in Python?
· Category: Python Programming
Short answer
Wrap risky code in a try block, catch specific exceptions with except, run success-only code in else, and guarantee cleanup in finally. Catch specific exceptions rather than a bare except:.
Steps
- Place the operation that might fail inside
try. - Catch expected exceptions with
except SpecificError:. - Use
elsefor code that runs only when no exception occurs. - Use
finallyfor cleanup that must always run.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
return None
except TypeError:
print("Invalid input type")
return None
else:
print("Division succeeded")
return result
finally:
print("Cleanup complete")
print(divide(10, 2))
print(divide(10, 0))
Tips
- Catch the most specific exception possible; catching
Exceptionbroadly can mask unexpected bugs. - Use
raisewithout an argument inside anexceptblock to re-raise the same exception after logging. - Context managers (
with) are often cleaner thantry/finallyfor resource management. Exceptionhierarchy matters: catch subclasses before their parent classes.
Common issues
- A bare
except:catchesSystemExit,KeyboardInterrupt, andGeneratorExit, which is usually undesirable. - Overly broad exception handling makes debugging difficult.
- Swallowing exceptions without logging or re-raising them hides problems.