Raising Exceptions
Python raises exceptions when built-in operations fail, and your own code can do the same. Raising an exception is the clearest way for a function to say "I can't do what you asked, and here's why".
The raise statement
Use raise followed by an exception object, usually with a helpful message. The function stops immediately, just as if Python itself had hit an error.
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
if amount > balance:
raise ValueError(f"Insufficient funds: balance is KES {balance}, requested KES {amount}")
return balance - amount
print(withdraw(1000, 300))
for request in [-50, 1500]:
try:
withdraw(1000, request)
except ValueError as error:
print("Refused:", error)
Why not just print a message and return None? Because the caller might ignore None and carry on with a wrong value. An exception can't be ignored by accident: either someone handles it, or the program stops and shows exactly what went wrong.
If nothing catches a raised exception, you get a normal traceback:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
set_age(-5)
Choosing the right exception type
Pick the built-in exception that best describes the problem, so callers can catch it sensibly:
| Use | When |
|---|---|
ValueError | The type is fine but the value isn't (negative age, empty name) |
TypeError | The argument is the wrong type entirely (text instead of a number) |
KeyError / LookupError | Something you looked up doesn't exist |
FileNotFoundError | A required file is missing |
PermissionError | The user isn't allowed to do this |
NotImplementedError | A method that subclasses are supposed to write |
RuntimeError | Something went wrong that doesn't fit any other category |
def area(width, height):
if not isinstance(width, (int, float)) or not isinstance(height, (int, float)):
raise TypeError("width and height must be numbers")
if width <= 0 or height <= 0:
raise ValueError("width and height must be positive")
return width * height
for args in [(4, 5), (4, "5"), (4, -5)]:
try:
print(area(*args))
except (TypeError, ValueError) as error:
print(f"{type(error).__name__}: {error}")
Creating your own exceptions
For bigger programs, define custom exception classes. They make error handling more precise, because callers can catch exactly your problem and nothing else. A custom exception is a class that inherits from Exception (classes are explained in Classes & Objects and Inheritance).
class BankError(Exception):
"""Base class for all errors in our banking app."""
class InsufficientFundsError(BankError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
shortfall = amount - balance
super().__init__(f"You need KES {shortfall} more to withdraw KES {amount}")
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
account = Account("Fatuma", 2000)
try:
account.withdraw(2600)
except InsufficientFundsError as error:
print("Error:", error)
print("Shortfall:", error.amount - error.balance)
except BankError:
print("Some other banking problem")
Name custom exceptions with an Error ending. A shared base class (here BankError) lets callers catch every error from your app with one except, or a specific one when they need to.
Re-raising and chaining exceptions
Re-raise with a bare raise
Inside an except block, raise on its own re-raises the current exception. This is handy when you want to log a problem but still let the caller deal with it.
def parse_score(text):
try:
return int(text)
except ValueError:
print(f"Logging: bad score {text!r}")
raise
try:
parse_score("9o")
except ValueError as error:
print("Caller saw:", error)
Translate an error with raise ... from
Sometimes a low-level error should become a clearer, higher-level one. raise NewError(...) from original does this while keeping the original attached as the "cause", so no debugging information is lost.
class InvalidAgeError(Exception):
pass
def load_age(text):
try:
return int(text)
except ValueError as error:
raise InvalidAgeError(f"Age must be a number, got {text!r}") from error
try:
load_age("twenty")
except InvalidAgeError as error:
print(error)
print("Caused by:", repr(error.__cause__))
If this exception were not caught, the traceback would show both errors, joined by the line "The above exception was the direct cause of the following exception".
A note on assert
assert condition, "message" raises an AssertionError if the condition is false. It's useful for checking your own assumptions while developing, for example assert total >= 0. Don't use it to validate user input: assertions are skipped completely when Python runs with the -O (optimise) option.
You can only raise exception objects. raise "Something broke" fails with TypeError: exceptions must derive from BaseException. Write raise ValueError("Something broke") instead. Also avoid raising the generic Exception: callers then can't catch your error without catching everything else too.
Key points
raise SomeError("message")stops a function and reports a problem.- Choose a fitting built-in type, or create a custom class that inherits from
Exception. - A bare
raiseinsideexceptre-raises the current exception. raise NewError(...) from errorkeeps the original error as the cause.- Use
assertfor developer checks, never for validating input.
Tip: use the ← and → keys to move between pages.
