How does a try/except block work, and what happens if no matching except clause exists?
Short answer
Code in 'try' runs normally; if it raises an exception, Python looks for the FIRST 'except' clause matching that exception's type (checked top to bottom) and runs it — if none match, the exception propagates up the call stack, potentially crashing the program if never caught…
Advertisement
AModel answer
Code in 'try' runs normally; if it raises an exception, Python looks for the FIRST 'except' clause matching that exception's type (checked top to bottom) and runs it — if none match, the exception propagates up the call stack, potentially crashing the program if never caught anywhere.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid value")Real-world example
Gracefully handling a division-by-zero or invalid-input error instead of letting the program crash with an unhandled traceback.
Likely follow-ups
- What happens if you put a more GENERAL exception type's except clause BEFORE a more SPECIFIC one?
Related topics