Search code examples
pythontraceback

Is there any way to access nested or re-raised exceptions in python?


A common pattern in python is to catch an error in an upstream module and re-raise that error as something more useful.

try:
    config_file = open('config.ini', 'r')
except IOError:
    raise ConfigError('Give me my config, user!')

This will generate a stack trace of the form

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
__main__.ConfigError: Give me my config, user!

Is there any way to access the wrapped exception in order to generate a stack trace more like this?

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
__builtin__.IOError: File Does not exist.
Exception wrapped by:
  File "<stdin>", line 4, in <module>
__main__.ConfigError: Give me my config, user!

EDIT:

The problem i'm trying to defeat is that some 3rd party code can wrap exceptions up to 3 times and I want to be able to determine the root cause, i.e. a generic way to inspect the exception stack and determine the root cause of an exception without having to add any extra code to 3rd party modules.


Solution

  • This is known as Exception Chaining and is suported in Python 3.

    PEP 3134: http://www.python.org/dev/peps/pep-3134/

    In Python 2, the old exception is lost when you raise a new one, unless you save it in the except block.