Sub topic 5
Raising and catching your exception
This chapter assumes you can write a class that inherits from Exception and that you know the basic try, except, and raise syntax. It covers how a custom exception behaves when you raise it and when you catch it. That includes how Python matches handlers, why their order matters, and how to re-raise safely.
Two ways to raise
The raise statement accepts either an exception instance or an exception class. Here is a small base class and a subclass to work with, followed by a function that raises the subclass:
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
def read_setting(settings, key):
if key not in settings:
raise ConfigError(f"missing {key!r}")
return settings[key]
try:
read_setting({"debug": True}, "database_url")
except AppError as exc:
print(f"{type(exc).__name__}: {exc}")This prints ConfigError: missing 'database_url'. The handler names AppError, but the object it receives is a ConfigError. type(exc).__name__ shows the real class.
If you raise a class, Python calls it with no arguments to build the instance. These two lines are equivalent:
raise ConfigError
raise ConfigError()In both cases str(exc) is an empty string. Raising a bare class is acceptable when the class name says everything. In most cases you should pass a message, because a traceback that ends in ConfigError with nothing after it gives the reader little to act on.
Anything you raise must derive from BaseException. Raising anything else, such as a string, fails:
try:
raise "something went wrong"
except TypeError as exc:
print(exc)This prints exceptions must derive from BaseException. Python replaces your intended error with a TypeError. Subclass Exception, not BaseException. BaseException also covers KeyboardInterrupt and SystemExit, which an ordinary except Exception is meant to let through.
How Python matches a handler
An except SomeClass clause matches when the raised object is an instance of SomeClass. That includes instances of any subclass. This is the same test as isinstance(exc, SomeClass).
| Handler | Catches a `ConfigError`? | Why |
|---|---|---|
| `except ConfigError` | Yes | Exact class |
| `except AppError` | Yes | `ConfigError` is a subclass of `AppError` |
| `except Exception` | Yes | `AppError` derives from `Exception` |
| `except KeyError` | No | Unrelated class |
| `except BaseException` | Yes | Top of the hierarchy |
Because of this rule, a single base class lets callers choose how precisely to catch. A caller who cares about configuration problems catches ConfigError. A caller who wants any failure from your package catches AppError. Designing that structure is the subject of a later chapter. Here you only need to know that matching follows inheritance.
Handler order matters
When a try statement has several except clauses, Python checks them from top to bottom. It runs the first one that matches and skips the rest. Python does not look for the most specific match.
try:
raise ConfigError("bad value")
except AppError:
print("base handler")
except ConfigError:
print("specific handler")This prints base handler. The ConfigError clause can never run, because every ConfigError is also an AppError. Python does not warn you about this, although linters such as pylint and Ruff can. Put the most specific class first:
try:
raise ConfigError("bad value")
except ConfigError:
print("specific handler")
except AppError:
print("base handler")Now the output is specific handler. Any other AppError still reaches the second clause.
Catching several classes at once
To handle unrelated exceptions the same way, give except a tuple. The parentheses are required:
def load_port(settings):
try:
return int(read_setting(settings, "port"))
except (ConfigError, ValueError) as exc:
print(f"using default port because: {exc}")
return 8000
print(load_port({}))
print(load_port({"port": "abc"}))
print(load_port({"port": "9000"}))The first call fails inside read_setting with a ConfigError. The second fails inside int with a ValueError. Both land in the same handler. The third succeeds and returns 9000.
Use a tuple only when the handling really is identical. If the two cases need different responses, write two clauses.
Re-raising with a bare raise
Sometimes a handler wants to do something, such as log or clean up, and then let the error continue upward. Write raise with nothing after it. It re-raises the exception currently being handled, with its original traceback intact:
def start(settings):
try:
return read_setting(settings, "database_url")
except ConfigError as exc:
print(f"startup failed: {exc}")
raise
try:
start({})
except AppError as exc:
print(f"caller saw: {type(exc).__name__}")The output has two lines. First startup failed: missing 'database_url', then caller saw: ConfigError.
You may be tempted to write raise exc instead. It works, but it adds an extra traceback line pointing at the re-raise statement, which clutters the output. A bare raise is the idiom for "pass this along unchanged".
else and finally
A try statement can also have else and finally clauses. They matter most when you work with custom exceptions, because they keep the try block small.
elseruns only if thetryblock finished without raising.finallyalways runs, whether or not an exception occurred, and even if a handler returns.
def run(settings):
try:
url = read_setting(settings, "database_url")
except ConfigError as exc:
print(f"config problem: {exc}")
return None
else:
print(f"connecting to {url}")
return url
finally:
print("run finished")
run({"database_url": "db://localhost"})
run({})The first call prints connecting to db://localhost and then run finished. The second prints config problem: missing 'database_url' and then run finished.
Keep the try block to the single call that can raise your exception. If you wrap ten lines in it, a ConfigError raised by an unrelated line gets handled by code that was written for a different failure. Putting the follow-up work in else makes the boundary clear.
What happens when nobody catches it
If no handler matches, the exception moves up to the calling function and Python repeats the search there. This continues until a handler matches or the call stack runs out. If it runs out, Python prints the traceback and exits with a non-zero status.
This search is why a well-named exception pays off. If the traceback prints ConfigError: missing 'database_url', the reader knows what failed and which key to check, without opening the source.
The as name disappears
The name after as exists only inside the except block. Python deletes it when the block ends, to avoid keeping the traceback, and everything it references, alive longer than needed. If you need the exception afterwards, copy it to another name:
saved = None
try:
raise ConfigError("example")
except ConfigError as exc:
saved = exc
print(saved)
try:
print(exc)
except NameError as name_error:
print(f"NameError: {name_error}")The first print shows example. The second lookup fails with a NameError because exc no longer exists.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| A specific handler never runs | A base-class clause appears above it | Order clauses from specific to general |
| `TypeError: exceptions must derive from BaseException` | You raised a string or other non-exception | Raise an instance of a class that inherits from `Exception` |
| `RuntimeError: No active exception to reraise` | Bare `raise` used outside an `except` block | Raise a new exception, or move the `raise` inside the handler |
| `NameError` on the exception variable | Used `exc` after the `except` block ended | Assign it to another name inside the block |
| Unrelated bugs get swallowed | The `try` block wraps too much code | Narrow the `try` and move the rest to `else` |
| Empty message in the traceback | Raised the bare class with no arguments | Pass a message that names the failing value |
Exercise
Given the classes AppError and ConfigError from this chapter, what does the following code print, and why? try: raise ConfigError("bad") except ValueError: print("value") except AppError: print("app") except ConfigError: print("config") finally: print("done")
Show answer
It prints "app" and then "done". ConfigError is not a ValueError, so the first clause is skipped. ConfigError is a subclass of AppError, so the second clause matches and runs. Python stops checking after the first match, so the ConfigError clause is never reached. The finally block always runs, so "done" is printed last.
Exercise
A function catches a ConfigError, prints a log line, and wants the caller to still receive the same exception with its original traceback. What should the last statement of the handler be, and why is it better than "raise exc"?
Show answer
A bare "raise". It re-raises the exception being handled without changing it. "raise exc" also works but adds an extra traceback entry pointing at the re-raise line, which makes the traceback harder to read.