Exception Chaining in Python 3

How can I raise an exception in Python and attach another exception as extra info.
That’s called exception chaining. (This article is AI generated. I’ll rewrite it on occasion.)


1. Using raise ... from ...

try:
    int("abc")
except ValueError as e:
    raise RuntimeError("Parsing failed") from e

Output:

RuntimeError: Parsing failed

The above exception was the direct cause of the following exception:
ValueError: invalid literal for int() with base 10: 'abc'

from e attaches the original exception as __cause__.


2. Using raise ... inside an except block (implicit chaining)

try:
    int("abc")
except ValueError:
    raise RuntimeError("General error")

Python automatically sets __context__ here, so the original exception is shown in the traceback, even without from.


3. Storing it as an attribute

If you don’t want chaining but just want to keep the original exception as information, you can save it in your own exception class:

class MyError(Exception):
    def __init__(self, message, original=None):
        super().__init__(message)
        self.original = original

try:
    1/0
except ZeroDivisionError as e:
    raise MyError("Custom error", original=e)

Then you can access .original when catching the exception.



Beitrag veröffentlicht

in

von

Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert