Sub topic 3
Your first custom exception
This chapter assumes you can read and write basic Python functions and classes, and that you have used try, except, and raise. You should also be comfortable with simple inheritance. By the end you will be able to write a custom exception class, choose its parent class, and predict how it behaves without adding any methods.
What a custom exception is
A custom exception is a class that inherits, directly or indirectly, from Python's built-in Exception. Python does not treat it specially. The raise statement accepts any instance of a class derived from BaseException, and except matches by class using the same rules as isinstance. So defining a new exception means defining a new class and choosing its parent.
The smallest useful version has a name and a docstring:
class ConfigError(Exception):
"""Raised when configuration is missing or invalid."""
def read_setting(settings, key):
try:
return settings[key]
except KeyError:
raise ConfigError(f"missing {key!r}")
try:
read_setting({}, "database_url")
except ConfigError as exc:
print(f"{type(exc).__name__}: {exc}")The output is:
ConfigError: missing 'database_url'The class body has no methods. A docstring is a valid class body on its own, so pass is unnecessary. The docstring also documents the class, which later chapters cover in more detail.
What you get for free
Because ConfigError inherits from Exception, it already has the standard exception machinery. The most important parts are in the table.
| Inherited member | What it does |
|---|---|
| `args` | A tuple of the positional arguments passed to the constructor. |
| `__str__` | Builds the message shown by `print(exc)` and in tracebacks. |
| `__repr__` | Shows the class name and `args`, for example `ConfigError('x')`. |
| `__traceback__` | The traceback attached when the exception is raised. |
| `__cause__`, `__context__` | Links to related exceptions, used for chaining. |
| `add_note()` | Attaches extra text to the exception (Python 3.11 and later). |
The behavior of args and __str__ is easy to get wrong, so check it directly:
class ConfigError(Exception):
"""Raised when configuration is missing or invalid."""
one = ConfigError("missing 'database_url'")
two = ConfigError("missing 'database_url'", "settings.toml")
none = ConfigError()
print(one.args)
print(str(one))
print(repr(one))
print(str(two))
print(repr(none))
print(repr(str(none)))The output is:
("missing 'database_url'",)
missing 'database_url'
ConfigError("missing 'database_url'")
("missing 'database_url'", 'settings.toml')
ConfigError()
''The rules are:
- With one argument,
str(exc)is that argument converted to a string. - With several arguments,
str(exc)is the string form of the wholeargstuple. This is rarely what you want to show a user. - With no arguments,
str(exc)is an empty string. A traceback then ends with just the class name, which gives a reader very little to work with.
In practice, always raise your exception with a single descriptive message until you have a reason to do more. Chapters later in this tutorial cover custom __init__ methods and __str__.
Choosing the parent class
The parent decides which except clauses catch your exception. You have three realistic choices.
| Parent | Use it when | Consequence |
|---|---|---|
| `Exception` | The error is specific to your code and has no good built-in match. | Caught by `except Exception` and by your own class. This is the default choice. |
| A specific built-in such as `ValueError` or `LookupError` | Your error is a refined version of that built-in. | Existing code that catches the built-in also catches yours. |
| `BaseException` | Almost never. | Escapes `except Exception`. See the warning below. |
BaseException sits at the top of the hierarchy. Exception is one of its children, next to KeyboardInterrupt, SystemExit, and GeneratorExit. Those three signal that the program or interpreter should stop, not that a normal operation failed.
The diagram shows where a typical custom exception sits.
Inheriting from a built-in
Subclassing a built-in keeps compatibility with code that already handles it. Suppose callers of a function used to receive ValueError and you want a more specific error without breaking them:
class InvalidPortError(ValueError):
"""Raised when a port number is not an integer between 1 and 65535."""
def parse_port(raw):
try:
port = int(raw)
except ValueError:
raise InvalidPortError(f"not an integer: {raw!r}")
if not 1 <= port <= 65535:
raise InvalidPortError(f"out of range: {port}")
return port
try:
parse_port("70000")
except ValueError as exc:
print(type(exc).__name__, exc)The output is InvalidPortError out of range: 70000. The except ValueError clause catches it because every InvalidPortError is also a ValueError.
The trade-off is that your exception now makes the same promise as the built-in. If a caller expects every ValueError to mean "bad argument", then raising it for an unrelated failure will mislead them. Pick a built-in parent only when the meaning really matches.
A base class for your package
Once a project has more than one custom exception, give them a shared parent that itself derives from Exception:
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
try:
raise ConfigError("missing 'database_url'")
except AppError as exc:
print(f"{type(exc).__name__}: {exc}")The output is ConfigError: missing 'database_url'.
The handler names AppError, but the object is a ConfigError. A caller can now catch everything your package raises on purpose with one clause, and let genuine bugs such as TypeError pass through. Designing larger hierarchies is the subject of a later chapter. For now, the point is that this base class is just another empty subclass.
Checking what you built
Two built-in functions help you confirm the relationships. The __mro__ attribute lists the classes Python searches, in order.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
err = ConfigError("bad")
print(isinstance(err, AppError))
print(issubclass(ConfigError, Exception))
print(issubclass(ConfigError, ValueError))
print([cls.__name__ for cls in ConfigError.__mro__])The output is:
True
True
False
['ConfigError', 'AppError', 'Exception', 'BaseException', 'object']An except clause matches an exception when isinstance(exc, ThatClass) is true. Handlers are checked from top to bottom, and the first match wins. Put the more specific class before the more general one, or the specific handler will never run:
try:
raise ConfigError("missing 'database_url'")
except AppError:
print("general handler")
except ConfigError:
print("specific handler, never reached")This prints general handler.
Where the class lives
Define exceptions in a module that other modules can import, commonly named errors.py or exceptions.py. Two reasons make this worth doing from the start:
- Callers need to import the class to write
except ConfigError. If it is defined inside a function or buried in a large module, importing it is awkward or creates circular imports. - The module name appears in tracebacks for uncaught errors, for example
myapp.errors.ConfigError: missing 'database_url'. A stable location makes those messages easier to search for.
Never define the class inside the function that raises it. Each call would create a new, distinct class, and no caller could name it in an except clause.
Common mistakes in a first exception
- Raising the class with no message.
raise ConfigErrorworks, because Python creates an instance with no arguments. The traceback then shows only the class name. Preferraise ConfigError("what went wrong"). - Passing several positional arguments and printing the exception. The output is the
argstuple, parentheses included. Use one message string, or define__str__as shown in a later chapter. - Inheriting from
BaseException. The warning above explains the cost. - Catching your class too broadly.
except Exceptioncatches your errors, but it also catches bugs you want to see. Catch your own base class when you mean "errors from my package". - Overriding
__init__without callingsuper().__init__(). The exception still works, butargsstays empty and the message may be lost. A later chapter covers this case. For now, avoid overriding__init__until you need to. - Raising an instance of a class that is not an exception.
raise object()fails withTypeError: exceptions must derive from BaseException. A class that merely looks like an exception does not qualify.
Exercise
You write class PaymentError(Exception): """Payment failed.""", then run print(str(PaymentError("card declined", 402))). What does it print, and how would you change the call so that it prints only card declined?
Show answer
It prints ('card declined', 402), because with more than one argument str() returns the string form of the args tuple. Pass only the message, as in PaymentError("card declined"). This prints card declined. If you also need the code, store it as an attribute with a custom __init__, which a later chapter explains.
Exercise
A function currently raises ValueError for a bad port. You want to raise a more specific InvalidPortError without breaking callers who write except ValueError. Which parent class should InvalidPortError use, and why?
Show answer
Use ValueError as the parent: class InvalidPortError(ValueError). Every InvalidPortError is then also a ValueError, so existing except ValueError handlers still catch it, while new code can catch InvalidPortError specifically.