Python Try…Except
Errors that happen at runtime are exceptions. Catch them with try / except; clean up with finally.
The shape
PYTHON
try:
n = int('not a number')
except ValueError as e:
print('Bad input:', e)
else:
print('Parsed', n) # only if no exception
finally:
print('Always runs')
Catch the specific type
| Common exception | When it happens |
|---|---|
ValueError | Right type, wrong value (int('abc')). |
TypeError | Wrong type ('a' + 1). |
KeyError | Missing dict key. |
IndexError | List index out of range. |
FileNotFoundError | File doesn't exist. |
ZeroDivisionError | Division by zero. |
Catch multiple types
PYTHON
try:
risky()
except (ValueError, KeyError) as e:
print('handled:', e)
Raising your own
PYTHON
def deposit(amount):
if amount <= 0:
raise ValueError(f'amount must be positive: {amount}')
Custom exception classes
PYTHON
class PaymentDeclined(Exception):
pass
raise PaymentDeclined('Card expired')
Don't swallow exceptions silently
PYTHON
# ✗ Worst form — hides every bug
try:
work()
except:
pass
# ✓ At minimum log it
import logging
try:
work()
except Exception:
logging.exception('work() failed')
Tip: EAFP — "Easier to Ask Forgiveness than Permission" — is the Pythonic way. Try the operation; catch the specific exception if it fails. Beats checking every precondition first.
Example
Example
try:
n = int('not a number')
except ValueError as e:
print('Bad input:', e)
else:
print('Parsed', n)
finally:
print('Always runs')
Try it Yourself »
Exercise
Block that always runs after try, regardless of outcome.
try: ...
except: ...
: cleanup()
Seven letters.
Discussion
Loading…