Sub topic 9
Raising exceptions with raise
This chapter assumes you can already catch exceptions with try and except, read a traceback, and write a basic class. It covers the other side of error handling: signaling a problem yourself with raise.
What raise does
The raise statement creates an exception and starts propagation. Python stops executing the current statement and looks for a matching handler in the current function. If it finds none, it leaves the function and checks the caller, and so on up the call stack. If no handler matches anywhere, the interpreter prints the traceback and exits the program or thread.
The traceback's last line points at the raise statement. That line is the first place a reader will look, so the exception type and message you choose are the main information you give them.
The forms of raise
raise accepts an exception instance, an exception class, or nothing at all.
def set_age(age):
if not isinstance(age, int):
raise TypeError(f"age must be int, got {type(age).__name__}")
if age < 0:
raise ValueError(f"age must be >= 0, got {age}")
return age
for value in (30, -5, "ten"):
try:
print(set_age(value))
except (TypeError, ValueError) as exc:
print(f"{type(exc).__name__}: {exc}")This prints 30, then ValueError: age must be >= 0, got -5, then TypeError: age must be int, got str.
Raising an instance
raise ValueError("message") is the usual form. You build the object, so you control its arguments. The arguments are stored in the args tuple, and str(exc) shows the message.
Raising a class
If you give raise a class, Python calls it with no arguments to create the instance. These two statements are equivalent:
try:
raise ValueError
except ValueError as exc:
print(repr(exc))
print(exc.args)The output is ValueError() and (). An exception with no message makes a poor traceback, so use the bare class form only when the type alone says everything. raise NotImplementedError is a common example.
Bare raise
A raise with no expression re-raises the exception currently being handled. It only works while an exception is active, which means inside an except block or in a function called from one. Anywhere else it fails:
try:
raise
except RuntimeError as exc:
print(exc)This prints No active exception to reraise. The next chapter covers re-raising and logging in detail.
Only exceptions can be raised
The object you raise must be an instance or subclass of BaseException. Anything else produces a TypeError:
try:
raise "something went wrong"
except TypeError as exc:
print(exc)The message is exceptions must derive from BaseException. In Python 2 you could raise strings. In Python 3 you cannot.
Choosing the exception type
Callers decide what to catch based on the type, so pick the most specific built-in that describes the problem. Do not default to Exception for everything.
| Situation | Exception to raise |
|---|---|
| Right type, unacceptable value | `ValueError` |
| Wrong type for an argument | `TypeError` |
| Missing key in a mapping you implement | `KeyError` |
| Index outside a sequence you implement | `IndexError` |
| Either of the two lookup failures, as a base | `LookupError` |
| Missing attribute in `__getattr__` | `AttributeError` |
| Abstract method not overridden | `NotImplementedError` |
| Operation not valid in the current state | `RuntimeError` or a custom class |
| Missing file or failed system call | `OSError` subclasses such as `FileNotFoundError` |
A custom class is better than RuntimeError when callers need to handle your error separately. Defining your own classes is covered in a later chapter.
A common mistake is mixing up NotImplementedError and NotImplemented. NotImplementedError is the exception you raise. NotImplemented is a constant that binary operator methods such as __add__ return to tell Python to try the other operand. Raising NotImplemented fails with a TypeError because it is not an exception.
Writing useful messages
A good message names the problem and shows the offending value. It is written for someone reading a log at 3 a.m. with no access to your debugger.
- Include the bad value, using
!rso strings show their quotes:f"unknown mode {mode!r}". - Include what was expected:
f"expected one of {sorted(MODES)}, got {mode!r}". - Do not include secrets such as passwords or tokens. Messages end up in logs and error trackers.
Python 3.11 added add_note(), which attaches extra lines to an exception after it is created. The notes appear below the message in the traceback:
try:
try:
raise ValueError("bad record")
except ValueError as exc:
exc.add_note("while loading row 17 of users.csv")
raise
except ValueError as exc:
print(exc.__notes__)The output is ['while loading row 17 of users.csv']. Notes are useful when a lower layer raises and a higher layer knows the context.
Raising inside an except block
When you raise a new exception while handling another one, Python records the original in the new exception's __context__ attribute. The traceback then shows both, joined by the line "During handling of the above exception, another exception occurred".
try:
try:
int("x")
except ValueError:
raise KeyError("missing")
except KeyError as exc:
print(type(exc.__context__).__name__)
print(exc.__suppress_context__)This prints ValueError and False. The context is set implicitly. If the new exception is a deliberate translation of the old one, write raise KeyError("missing") from exc instead, which sets __cause__ and changes the traceback wording. That form is covered in the chaining chapter.
Where to put raise statements
Validate at the boundary
Check arguments where data enters your code, such as public functions, constructors, and parsers. Raise immediately so the traceback points at the bad input and not at some later line that failed because of it. This is the "fail fast" pattern.
def average(values):
if not values:
raise ValueError("average() needs at least one value")
return sum(values) / len(values)Without the check, an empty list would raise ZeroDivisionError with a message about division, which says nothing about the real mistake.
raise versus assert
assert condition, message raises AssertionError when the condition is false. Python removes assert statements entirely when run with -O. Use assert for internal sanity checks that should never fail. Use raise for validating input from callers or from outside the program, because that check must always run.
Do not return error codes
Returning None or -1 to signal failure lets callers forget to check, and the error then surfaces far from its cause. An exception cannot be ignored by accident. Reserve None for cases where "no result" is a normal outcome, such as dict.get.
Edge cases
Exceptions pass through finally
When a raise leaves a try block with a finally clause, the finally code runs before the exception continues upward. Cleanup is therefore guaranteed even though the function exits early.
def work():
try:
raise OSError("disk unavailable")
finally:
print("cleanup done")
try:
work()
except OSError as exc:
print(f"caught: {exc}")The output is cleanup done and then caught: disk unavailable.
StopIteration inside generators
Since Python 3.7, a StopIteration that escapes a generator function is converted to RuntimeError. In a generator, return is the way to end iteration. Raising StopIteration by hand is a bug in generator code.
Raising is not free, but it is cheap enough
Raising and catching an exception costs more than an if check, but the difference only matters in tight loops where failure is common. Python's style, known as EAFP ("easier to ask forgiveness than permission"), accepts that cost. Do not avoid raise for performance reasons without measuring first.
Do not raise in a way that hides the cause
Writing raise Exception("failed") in an except block throws away the original type and, unless you chain it, makes the original hard to find. Keep the cause attached with from, or let the bare raise pass the original through.
Summary of rules
- Raise an instance with a clear message that includes the bad value.
- Choose the most specific built-in type, or define your own.
- Validate early and raise at the boundary.
- Use
raisefor runtime checks andassertonly for internal invariants. - Remember that only
BaseExceptionsubclasses can be raised.
Exercise
Write the behavior of a function withdraw(balance, amount) that must reject an amount that is not a number, a negative amount, and an amount larger than the balance. Which exception type fits each case, and what should the message contain?
Show answer
Use TypeError when amount is not an int or float, for example raise TypeError(f"amount must be a number, got {type(amount)._name_}"). Use ValueError when amount is negative, because the type is right but the value is not acceptable, for example raise ValueError(f"amount must be >= 0, got {amount}"). For an amount above the balance, ValueError works for a simple function, but a custom InsufficientFundsError is better when callers need to handle it separately. Each message names the problem and shows the offending value, and each check comes first in the function so the traceback points at the bad input.
Exercise
What happens when the interpreter executes raise ValueError, with no parentheses and no message, and what does the resulting exception's args attribute contain?
Show answer
Python calls the class with no arguments to create an instance, then raises it. The exception is a normal ValueError, and its args attribute is the empty tuple (). The traceback shows only the type name with no message, which is why a message is usually worth adding.