Sub topic 5
Raising and catching your exception
This chapter assumes you can write a basic try/except block and have already defined a class that subclasses Exception. Here you will raise that class and catch it correctly.
Raising an exception
The raise statement accepts an exception instance or an exception class. Python creates an instance from a class with no arguments. Pass a message when you raise, because a bare class gives the reader nothing to act on.
class ConfigError(Exception):
"""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({"host": "localhost"}, "database_url")
except ConfigError as exc:
print(f"{type(exc).__name__}: {exc}")This prints ConfigError: missing 'database_url'. The as exc clause binds the instance to a name. Python deletes that name when the except block ends, so copy the value to another variable if you need it later.
If nothing catches the exception, it travels up the call stack. Python then prints a traceback that ends with the class name and message, and the program exits with an error.
How Python picks a handler
Python checks the except clauses from top to bottom. It runs the first clause whose class matches the raised exception, or matches one of its parent classes. Later clauses are skipped.
Because a parent class matches its subclasses, put the most specific class first and the general one after it.
A complete handler
The next example uses a base class, a subclass, and every part of the try statement.
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]
def start(settings):
try:
url = read_setting(settings, "database_url")
except ConfigError:
print("using default database")
url = "sqlite:///:memory:"
except AppError:
print("unexpected application error")
raise
else:
print("configuration loaded")
finally:
print("startup check finished")
return url
print(start({}))
print(start({"database_url": "postgres://db/app"}))Each part has one job:
except ConfigErrorhandles the specific case you know how to recover from.except AppErrorcatches any other error from your application. A bareraiseinside the handler re-raises the exception that is being handled, with its original traceback.elseruns only if thetrybody raised nothing.finallyalways runs, whether or not an exception occurred.
Choosing what to catch
Catch a custom exception only where you can do something useful about it. Useful actions include recovering, retrying, translating it into a user message, or adding context and re-raising. If you can't do any of these, let the exception pass to the caller.
You can list several classes in one clause with a tuple, for example except (ConfigError, KeyError):. Catching a base class such as AppError is also a deliberate choice. It handles every current and future subclass, so a caller doesn't need to know the full list.
Avoid except Exception: unless you are at the top level of a program, such as a request handler or a job runner. It hides bugs like TypeError that your code should not swallow.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| General class listed before a specific one | The specific handler never runs | Order clauses from specific to general |
| `raise exc` inside a handler to re-raise | Adds a redundant line to the traceback | Use a bare `raise` |
| Raising the class with no message | The traceback shows only the class name | Pass a descriptive message |
| Using `exc` after the `except` block | `NameError`, because Python deleted the name | Copy it to another variable first |
Exercise
In a function, you write except AppError: first and except ConfigError: second, where ConfigError subclasses AppError. A ConfigError is raised. Which handler runs, and what should you change?
Show answer
The AppError handler runs, because a subclass instance matches its parent class and Python uses the first matching clause. The ConfigError handler can never run. Swap the order so except ConfigError: comes first and except AppError: second.