Python Try..Except
Things go wrong at runtime: a file is missing, a user types letters where a number belongs, a network request times out. Python signals these situations by raising an exception. If nobody handles it, the program stops with a traceback. The try statement lets you catch exceptions and respond gracefully.
Basic try / except
try:
result = 10 / 0
print("This line never runs")
except ZeroDivisionError:
print("You can't divide by zero!")
print("The program keeps going.")You can't divide by zero!
The program keeps going.
Python runs the try block. As soon as an exception occurs, it jumps to a matching except block, skipping the rest of try.
Catching specific exceptions
Name the exceptions you expect. You can have several except blocks, or one that handles a tuple of types. as err gives you the exception object, whose text describes the problem:
def to_number(text):
try:
return int(text)
except ValueError as err:
print("ValueError:", err)
except TypeError as err:
print("TypeError:", err)
print(to_number("42"))
print(to_number("forty-two"))
print(to_number(None))42
ValueError: invalid literal for int() with base 10: 'forty-two'
None
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
None
Common built-in exceptions
| Exception | Raised when |
|---|---|
ValueError |
right type, wrong value: int("abc") |
TypeError |
wrong type: "a" + 1 |
KeyError |
missing dict key |
IndexError |
list index out of range |
AttributeError |
object has no such attribute |
NameError |
variable doesn't exist |
ZeroDivisionError |
dividing by zero |
FileNotFoundError |
opening a file that doesn't exist |
ImportError |
module can't be imported |
All of them inherit from Exception. Catching Exception catches nearly everything — use it only at the outermost level (for logging), never to silently hide bugs.
else and finally
| Block | Runs |
|---|---|
try |
always (until an exception) |
except |
only if a matching exception occurred |
else |
only if no exception occurred |
finally |
always, exception or not — for clean-up |
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print(f"{a}/{b}: cannot divide by zero")
else:
print(f"{a}/{b} = {result}")
finally:
print(" (division attempted)")
divide(9, 3)
divide(1, 0)9/3 = 3.0
(division attempted)
1/0: cannot divide by zero
(division attempted)
Keep the try block small and put the "success" code in else — that way you don't accidentally catch exceptions from code you didn't mean to protect.
Raising exceptions
Use raise to signal an error in your own code. Choose the most fitting built-in type and write a clear message:
def set_age(age):
if not isinstance(age, int):
raise TypeError("age must be an integer")
if age < 0 or age > 150:
raise ValueError(f"age out of range: {age}")
return age
for value in [30, -4, "old"]:
try:
print("accepted", set_age(value))
except (TypeError, ValueError) as err:
print(type(err).__name__, "-", err)accepted 30
ValueError - age out of range: -4
TypeError - age must be an integer
Custom exceptions
For errors specific to your program, define your own exception class by subclassing Exception:
class InsufficientFunds(Exception):
def __init__(self, needed, available):
super().__init__(f"need {needed}, only {available} available")
self.shortfall = needed - available
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFunds(amount, balance)
return balance - amount
try:
withdraw(100, 250)
except InsufficientFunds as err:
print("Error:", err)
print("Short by", err.shortfall)Error: need 250, only 100 available
Short by 150
Re-raising and chaining
Sometimes you want to log an error and let it continue upwards — a bare raise re-raises the current exception. To translate a low-level error into a higher-level one, use raise ... from ..., which keeps the original as the cause:
class ConfigError(Exception):
pass
def read_port(settings):
try:
return int(settings["port"])
except (KeyError, ValueError) as err:
raise ConfigError("invalid port setting") from err
try:
read_port({"port": "eighty"})
except ConfigError as err:
print(err)
print("caused by:", type(err.__cause__).__name__)invalid port setting
caused by: ValueError
Tip: "Easier to ask forgiveness than permission" (EAFP) is the Pythonic style: just try the operation and handle the exception, instead of checking every condition beforehand.
Test yourself
When does the else block of a try statement run?
- Always
- When an exception was caught
- When no exception occurred in the try block
- Only after finally
Which block is guaranteed to run whether or not an exception happened?
- except
- else
- finally
- raise
Which exception does {"a": 1}["b"] raise?
- IndexError
- ValueError
- KeyError
- NameError