Is it possible to automatically break into the debugger when a exception is thrown?

You don't want to break on every exception; idiomatic Python code uses exceptions heavily (EAFP) so you'd be continually breaking in unrelated code.

Instead, use pdb post-mortem: import pdb; pdb.pm(). This uses sys.last_traceback to inspect the stack including the locals at the throw point.


ipython supports this (http://ipython.org). from inside ipython, do

%pdb on

and from then on, it will automatically drop you inside the debugger whenever you get an exception.

note that you'll (probably) quickly tire of this in general use... every time you mistype something and get a syntax error, you'll have to exit the debugger. but it's sometimes useful.


I found what I was looking for in an answer to What is the simplest way of using Python pdb to inspect the cause of an unhandled exception?

Wrap it with that:

<!-- language: lang-py -->
def debug_on(*exceptions):
    if not exceptions:
        exceptions = (AssertionError, )
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except exceptions:
                pdb.post_mortem(sys.exc_info()[2])
        return wrapper
    return decorator

Example:

@debug_on(TypeError)
def buggy_function()
    ....
    raise TypeError