|Ned Batchelder : Blog | Code | Text | Site|
Re-throwing exceptions in Python
» Home : Blog : November 2007
When dealing seriously with error handling, an important technique is to be able to manipulate exceptions in ways other than simply throwing and catching them. One of these is to re-throw exceptions.
The simplest way to do this is if you need to perform a little work after the catch, but then immediately re-throw. This can be done with a simple raise statement:
Here the raise statement means, "throw the exception last caught". This is a simple case, and I probably didn't need to remind you of it. But a more sophisticated technique is to catch an exception in one place, and raise it again in another.
For example, you may have a worker thread pre-fetching data from slow storage, and then on the main thread, the consumer of the data either gets the data or sees the exception that prevented him from getting the data.
Here's the simple implementation:
We store an exception in the object, and when retrieving the result, if there's an exception, we raise it. It works:
$ python delayed.py
The only problem is, the traceback for the exception shows the problem starting in get_result. When debugging problems, it's enormously helpful to know their real origin.
To solve that problem, we'll store more than the exception, we'll also store the traceback at the time of the original problem, and in get_results, we'll use the full three-argument form of the raise statement to use the original traceback:
Now when we run it, the traceback points to do_something_dangerous, called from do_work, as the real culprit:
$ python delayed.py
The three-argument raise statement is a little odd, owing to its heritage from the old days of Python when exceptions could be things other than instances of subclasses of Exception. This accounts for the odd tuple-dance we do on the saved exc_info.
It's easy to write code that does the right thing when everything is going well. It's much harder to write code that does a good job when things go wrong. Properly manipulating exceptions helps.