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 done output could be a nuisance in this case because it will happen in any case (caught or not caught). 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 this has the drawback of reducing the exception trace to exactly this raise
while the raise
without argument retains the original exception trace.
In Python 3 you can keep the original stack by using the raise
-from
syntax:
raise ZeroDivisionError("Got an error") from e