Re-raising exceptions

suggest change

Sometimes you want to catch an exception just to inspect it, e.g. for logging purposes. After the inspection, you want the exception to continue propagating as it did before.

In this case, simply use the raise statement with no parameters.

try:
    5 / 0
except ZeroDivisionError:
    print("Got an error")
    raise

Keep in mind, though, that someone further up in the caller stack can still catch the exception and handle it somehow. The "Got an error" message is printed whether or not a caller later catches the exception. So it might be a better idea to raise a different exception, containing your comment about the situation as well as the original exception:

try:
    5 / 0
except ZeroDivisionError as e:
    raise ZeroDivisionError("Got an error", e)

But the new exception's own traceback starts at this raise. Python 3 still prints the original as context (During handling of the above exception, another exception occurred). A bare raise keeps the original traceback instead.

In Python 3 you can keep the original stack by using the raise-from syntax:

raise ZeroDivisionError("Got an error") from e

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents