In Python, how to drop into the debugger in an except block and have access to the exception instance?

ipdb.set_trace() doesn't quite trigger IPDB immediately. It triggers on the next trace event, which in your case, is after the except block ends.

Python 3 deletes the e variable at the end of the except block, to break traceback reference cycles. Unfortunately for you, that happens before IPDB can trigger.

One hacky workaround you could use would be to add another line after set_trace, so IPDB triggers on the 'line' event:

try:
    1/0
except ZeroDivisionError as e:
    import ipdb
    ipdb.set_trace()
    workaround = True

Another option would be to use post-mortem debugging, which doesn't need to wait for a trace event:

try:
    1/0
except ZeroDivisionError as e:
    import ipdb
    ipdb.post_mortem()

Post-mortem debugging has a number of important differences from regular debugging, though. It'll put you in the (usually dead) stack frame where the exception occurred, rather than the stack frame where the post_mortem call occurred. Those happen to be the same frame in your example, but they usually won't be. Having access to the stack frame where the exception was raised is pretty nice, and you can still navigate to the frame where the exception was caught (but no further, due to Python's unusual traceback system), but it's still a major difference.

Also, you can't step in post-mortem mode. Trying to run next or step will exit debugging.


Actually you can use post_mortem to access the traceback context

import ipdb; ipdb.post_mortem()

ipdb> e
ZeroDivisionError('division by zero',)

Tags:

Python