Custom exceptions let a caller catch exactly the failure that your own code knows about, instead of a generic Exception that could have come from anywhere at all. Exception chaining, which is the raise ... from ... syntax, then lets you keep the original error visible while you add your own explanation of what it means in this particular context.
The previous lesson in this module covered "Exceptions: try, except, else, finally, raise", and this lesson is the last one in the Python File Handling and Exceptions module.
Both of these ideas rest on one simple fact, which is that an exception is just a class. Subclass Exception and you have made a new kind of error. The raise and except clauses then work with it in exactly the same way that they work with the built-in errors.
Why would you define your own exception classes?
Because except ValueError is a promise that you cannot keep. If your function raises ValueError for bad input, then a caller cannot tell that apart from a ValueError that was raised deep inside a library that you called. A named exception type says precisely which layer produced the failure.
It also lets you build a small hierarchy. A caller who wants to handle everything that you can raise catches the base class, and a caller who cares about only one case catches the specific subclass.
class InventoryError(Exception):
"""Base class for every error this package raises."""
class InsufficientStock(InventoryError):
pass
class UnknownProduct(InventoryError):
pass
class Stock:
def __init__(self, counts):
self.counts = counts
def reserve(self, sku, amount):
if sku not in self.counts:
raise UnknownProduct(f"no product with id {sku!r}")
if self.counts[sku] < amount:
raise InsufficientStock(
f"only {self.counts[sku]} of {sku!r} left, wanted {amount}"
)
self.counts[sku] -= amount
return self.counts[sku]
stock = Stock({'A-1': 3})
try:
stock.reserve('A-1', 10)
except InsufficientStock as exc:
print('specific handler:', exc)
except InventoryError:
print('would catch any error from this package')
There are no rules about the names, but the conventions help everybody. Exception class names end in Error or Exception, and they are usually defined at module level so that callers can import them. Keep the base class as plain Exception unless you have a specific reason to derive from something else. Inheriting from ValueError is occasionally useful when you want the new type to satisfy an existing except ValueError in code that you do not control.
| Exception type | Raise it when |
|---|---|
ValueError | the value is the right type but has the wrong content |
TypeError | the value is not the right type at all |
KeyError | a lookup found nothing |
RuntimeError | the operation cannot continue in the current state |
How do you raise a custom exception with a useful message?
Instantiate it with a message and then give it to raise. The constructor accepts any number of arguments and stores them in args, so str(exc) gives you the message and repr(exc) shows the type and the arguments together.
class ValidationError(Exception):
def __init__(self, field, value, reason):
super().__init__(f"{field}={value!r} {reason}")
self.field = field
self.value = value
try:
raise ValidationError('temperature', -300, 'is below the minimum of 0')
except ValidationError as exc:
print('message :', exc)
print('field :', exc.field)
print('value :', exc.value)
Give the message the information that a person debugging the failure would need, which means the offending value, the limit that was exceeded, and the name that was not found. "Invalid input" is rarely enough, while "temperature -300 is below the allowed minimum of 0" is exactly what you want to read at two in the morning.
You can also give your exception class its own constructor when it needs more than a message, and you can add attributes so that the catcher can inspect the details in code instead of parsing the message string.
What does 'raise ... from ...' change about a traceback?
When an exception is raised while another one is being handled, Python attaches the original to the new one automatically as an implicit background detail. You see the words "During handling of the above exception, another exception occurred". The from keyword replaces that implicit link with an explicit one, and the wording changes to "The above exception was the direct cause of the following exception".
def load_settings(path):
try:
with open(path, encoding='utf-8') as handle:
return handle.read()
except OSError as exc:
raise RuntimeError(f"could not load settings from {path!r}") from exc
try:
load_settings('missing.ini')
except RuntimeError as exc:
print('message :', exc)
print('cause :', type(exc.__cause__).__name__)
print('cause msg :', exc.__cause__)
The important difference is not the wording. It is the __cause__ attribute. With an explicit from, the original exception is stored as __cause__, and the traceback renders both of them with the cause first. A caller can also inspect exc.__cause__ to get at the underlying failure in code.
There is a fourth possibility that is worth knowing. Leave the from keyword out and the original error is still attached, but as __context__ instead of __cause__. Both attributes exist on every exception. __context__ is set for you automatically, and __cause__ is only set when you ask for it.
How do you hide the original error when you want to?
raise NewError("message") from None suppresses the context completely. The traceback shows only the new exception, and __suppress_context__ becomes True. This is the right tool when the underlying error is noise for the reader, such as a retry that succeeded on the second attempt, or a low-level parse error that you have already turned into something meaningful.
def read_number(text):
try:
return int(text)
except ValueError:
raise ValueError(f"{text!r} is not a whole number") from None
try:
read_number('twelve')
except ValueError as exc:
print('clean message:', exc)
print('cause is hidden:', exc.__cause__ is None)
Use it sparingly. Suppressing a cause destroys the trail back to the original failure, and the next person who has to debug that code will find it much harder. If the original error carries information that somebody will need, then keep it and chain it explicitly.
When should you let an exception propagate untouched?
Most of the time, you should. If a lower layer already produces a clear and accurate message, then wrapping it adds a layer of noise instead of clarity. Chain the error when you are adding genuinely new information, such as the operation that failed, the identifier that was involved, or the thing that the caller should try next.
And if the fix belongs at the call site, then let the exception travel. A function that catches an error only to raise the identical error again is doing nothing except adding a stack frame.
def parse_port(text):
return int(text)
def start_server(text):
try:
port = parse_port(text)
except ValueError as exc:
raise RuntimeError(f"invalid port {text!r}") from exc
return f'listening on {port}'
try:
start_server('not-a-port')
except RuntimeError as exc:
print(exc)
print('caused by:', repr(exc.__cause__))
Next steps
- Subclass
Exceptionto make a named error type that callers can catch precisely. - Build a small hierarchy, with a base class for the whole family and subclasses for the specific cases.
- Use
raise ... from originalto state the causal link explicitly and to set__cause__. - Use
from Noneonly when the original context would genuinely mislead the reader. - Do not wrap an exception just to raise the same information again. Let it propagate.
Try it yourself: a domain error hierarchy
Design an exception hierarchy for a small inventory system. You need a base InventoryError, a subclass for "not enough stock", another one for "unknown product id", and another one for "the quantity must be a positive integer".
Then write a function that validates a restock order and raises the right type in each case, with messages that name the offending product and the numbers that were involved. Write a caller that catches the base class once and prints the message, and then write a second caller that catches only InsufficientStock and retries with a smaller quantity. Finally, chain one of your errors from an underlying KeyError, and print both __cause__ and __context__ so that you can see how Python stores them differently.