Sub topic 9
Raising exceptions with raise
This chapter assumes you can write and call Python functions, use try and except, and read a simple traceback. You have been catching exceptions so far. Here you will start signalling them yourself.
What raise does
The raise statement stops the current function and starts an exception travelling up the call stack. It travels until a matching except clause handles it or the program ends with a traceback.
You can give raise an exception instance or an exception class:
raise ValueError("age must be positive")
raise ValueErrorThe second form is shorthand. Python creates the instance for you by calling ValueError() with no arguments. Pass a message whenever you can. The message is what the reader sees in the traceback.
Validating input
The most common use of raise is rejecting bad input at the start of a function, before it does any work.
def set_age(age):
if not isinstance(age, int):
raise TypeError(f"age must be an int, got {type(age).__name__}")
if age < 0:
raise ValueError(f"age must be non-negative, 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}")Running this prints 30, then ValueError: age must be non-negative, got -5, then TypeError: age must be an int, got str. Each failure names the bad value, so the caller can fix it without a debugger.
Choosing the exception type
Pick the built-in type that matches the mistake. Callers write handlers based on the type, so a precise type makes handling easier.
| Situation | Exception |
|---|---|
| Right type, unacceptable value | `ValueError` |
| Wrong type of argument | `TypeError` |
| Missing dictionary key | `KeyError` |
| Index outside a sequence | `IndexError` |
| Method that subclasses must override | `NotImplementedError` |
| Anything else, with no better fit | a custom class (see the chapter on custom exceptions) |
Avoid raise Exception("something broke"). Callers can only catch it by catching every Exception, which also hides unrelated bugs.
What can be raised
Only objects derived from BaseException can be raised. Raising anything else is itself an error:
try:
raise "something went wrong"
except TypeError as exc:
print(exc)This prints exceptions must derive from BaseException. Python 2 allowed string exceptions, but Python 3 does not.
Bare raise
A raise with no argument re-raises the exception currently being handled. It is only meaningful inside an except block. Outside one, there is no active exception, so Python raises RuntimeError: No active exception to reraise. The next chapters cover re-raising in detail.
Common mistakes
- Using
assertto validate input. Assertions are removed when Python runs with the-Oflag, so the check can disappear. Useraisefor checks that must always run. - Returning an error value such as
Noneor-1instead of raising. Callers can ignore a return value without noticing. They cannot ignore an exception. - Writing vague messages like
"invalid". Include the value and the rule it broke. - Confusing
NotImplementedwithNotImplementedError. The first is a special value for binary operators. The second is the exception you raise.
Exercise
Write a function square_root(x) that raises TypeError if x is not an int or float, raises ValueError if x is negative, and otherwise returns x ** 0.5. Why is ValueError the better choice for the negative case than TypeError?
Show answer
def squareroot(x):
if not isinstance(x, (int, float)):
raise TypeError(f"x must be a number, got {type(x).name_}")
if x < 0:
raise ValueError(f"x must be non-negative, got {x}")
return x ** 0.5
A negative number has the right type but an unacceptable value. ValueError describes that. TypeError is for arguments of the wrong type, like a string.