Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab a reference on the last thrown exception

In the python and/or ipython interactive interpreter, how can I get name bound on the last unhandled exception? I.e. the equivalent of

>>> try:
...     1/0
... except Exception as potato:
...     pass
... 
>>> format(potato)
'integer division or modulo by zero'

Must be something like...

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> import sys
>>> potato = ???
like image 260
wim Avatar asked Jan 31 '13 03:01

wim


1 Answers

You can use sys.last_value for this:

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> sys.last_value
ZeroDivisionError('integer division or modulo by zero',)
>>> type(sys.last_value)
<type 'exceptions.ZeroDivisionError'>
like image 62
mgilson Avatar answered Sep 19 '22 03:09

mgilson