24

Is there a way to examine the last exception when in pdb/before entering pdb? (Using python 2.7.5).

Immediately (yes, I enter no other commands at all) after an exception being raised in my code, I do sys.exc_info(); this just results in (None, None, None). At this point, I can do pdb.pm(), and pdb starts at the point that the exception is raised.

I'd like to be able to examine this exception object (it is not stored in a variable before being raised).

There is nothing obviously helpful in http://docs.python.org/2/library/pdb.html or http://docs.python.org/2/library/sys.html

Edit: I know about set_trace. I'd like to examine the exception before I modify the code.

Marcin
  • 48,559
  • 18
  • 128
  • 201
  • [Get reference to the current exception](https://stackoverflow.com/questions/20797923/get-reference-to-the-current-exception) has an answer that works for my use case: getting the last thrown exception when stepping through with pdb. – zneak Dec 06 '17 at 23:50

5 Answers5

14

You can retrieve the latest exception in pdb/ipdb via:

__exception__

The above is actually a tuple of the (exception, message).

cdosborn
  • 3,111
  • 29
  • 30
13

Is this what you are looking for?

import pdb
try:
    1/0
except Exception as err:
    pdb.set_trace()

% test.py
--Return--
> /home/unutbu/pybin/test.py(8)<module>()->None
-> pdb.set_trace()
(Pdb) err
ZeroDivisionError('integer division or modulo by zero',)
(Pdb) quit

If you do not want to modify the code where the exception originates, you could instead redefine sys.excepthook:

import pdb
import sys
def excepthook(type, value, traceback):
    pdb.set_trace()
sys.excepthook = excepthook

1/0

% test.py
--Return--
> /home/unutbu/pybin/test.py(7)excepthook()->None
-> pdb.set_trace()
(Pdb) type
<type 'exceptions.ZeroDivisionError'>
(Pdb) value
ZeroDivisionError('integer division or modulo by zero',)
(Pdb) traceback
<traceback object at 0xb774f52c>
(Pdb) 
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
10

You can use sys.last_value:

>>> no_such_var
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'no_such_var' is not defined
>>> import sys
>>> sys.last_value
NameError("name 'no_such_var' is not defined",)
>>> sys.last_value.args
("name 'no_such_var' is not defined",)

>>> no_such_var
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'no_such_var' is not defined
>>> import pdb, sys
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) sys.last_value
NameError("name 'no_such_var' is not defined",)

NOTE: This solution is not perfect. The value is set when an exception is not handled and the interpreter prints an error message and a stack traceback. For example, if the exception is caught using try .. except .., sys.last_value is not set.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 32
    I get: `*** AttributeError: 'module' object has no attribute 'last_value'` – claymation Nov 24 '14 at 18:18
  • @claymation, That attribute is not set if there was no exception. Execute a statement that causes an exception. For example: `1/0` – falsetru Nov 25 '14 at 00:43
  • 8
    @falsetru `-> print 1 / 0`, `(Pdb) n`, `ZeroDivisionError: 'integer division or modulo by zero'`, `(Pdb) import sys`, `(Pdb) print sys.last_value`, `*** AttributeError: 'module' object has no attribute 'last_value'` - it does not exist (python 2.6) – Izkata Apr 24 '15 at 18:45
  • 1
    Per the documentation, that value is only set if the exception was fatal. – zneak Dec 06 '17 at 23:44
  • @zneak, Could you share the documentation url? – falsetru Dec 06 '17 at 23:46
  • @falsetru, you literally posted it yourself: http://docs.python.org/2/library/sys.html#sys.last_value – zneak Dec 06 '17 at 23:47
  • @zneak, But, there's no mentation about `fatal`. – falsetru Dec 06 '17 at 23:48
  • 1
    @falsetru, what is your interpretation of "These three variables are not always defined; they are set when an exception is **not handled** and the interpreter prints an error message and a stack traceback"? – zneak Dec 06 '17 at 23:48
  • @zneak, Ah, sorry for my poor English reading. Added that part in the answer. Thank you. – falsetru Dec 06 '17 at 23:53
  • 1
    I appreciate the attention that this is getting; but note that it still doesn't work when tracing through pdb. Try [this](https://pastebin.com/7Ld4TZaA) and see if you can get the exception from the (pdb) prompt. Alternatively, `set_trace()` before `1/0`, hit `n` and see if you can get the exception there. – zneak Dec 07 '17 at 00:00
  • @zneak, Isn't `try .. except ...` **handing** exception ? – falsetru Dec 07 '17 at 00:10
  • Yes, but what if my catch clause was like `(ZeroDivisionError, IOError, ValueError)` and I wanted to get the complete message without adding a temporary `... as exc` from pdb? As OP says: "I'd like to examine the exception before I modify the code." – zneak Dec 07 '17 at 00:12
  • @zneak, How about `import sys`, then `!sys.exc_info()`? (didn't put this in the answer because OP already tried sys.exc_info() and got `(None, None, None)`. – falsetru Dec 07 '17 at 00:21
  • 1
    @falsetru My comment was using `pdb` in a script, not the shell, similar to zneak's pastebin after your comment @-ing me – Izkata Dec 07 '17 at 01:40
2

You can run the script through pdb via python -m pdb -c continue script.py. It will enter post-mortem debugging on an uncaught exception and drop you in the pdb interface. Here you can examine sys.exc_info() in order to get the exception. For example:

$ echo "1 / 0" > script.py 
$ python -m pdb -c continue script.py 
Traceback (most recent call last):
  [...]
  File "/tmp/script.py", line 1, in <module>
    1 / 0
ZeroDivisionError: division by zero
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /tmp/script.py(1)<module>()
-> 1 / 0
(Pdb) !import sys
(Pdb) p sys.exc_info()
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x7f3adcf09148>)
(Pdb) interact
*interactive*
>>> import sys
>>> sys.exc_info()
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x7f3adcf09148>)
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • I only figured this out like two weeks ago myself, after using python for 12 years. It's actually a wonderful solution when available. – Marcin Oct 30 '19 at 14:51
  • `(, AttributeError("'Pdb' object has no attribute 'do_sys'"), )` on python 3.10 – Att Righ Sep 22 '22 at 17:54
  • ^ For the above I ended up having to use `!sys.exc_info()` which apparently executes on a different frame. – Att Righ Sep 23 '22 at 02:28
2

I bumped into this post, but none of the answers did what I needed, which was to repeat all of the error information (including the traceback) that was spewed before the pdb.pm() step in the question. Here's what worked for me in the end:

Add the following lines to your .pdbrc file:

import sys
import traceback
alias rethrow traceback.print_exception(sys.last_type, sys.last_value, sys.last_traceback)

Now, next time you're in a pdb environment, you can just type rethrow, and it will repeat all the error information from before you had typed pdb.pm().

Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57