Take a link to the last exception thrown

In the python and / or ipython interactive interpreter, how can I bind a name to the last unhandled exception? That is the equivalent

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

It 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 = ???
+5
source share
2 answers

You can use sys.last_valuefor 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'>
+5
source

You can invoke ipythonwith a switch --pdbto dump you into the python debugger (pdb) when an unhandled exception occurs.

$ ipython --pdb
In [1]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-2-05c9758a9c21> in <module>()
----> 1 1/0

ZeroDivisionError: integer division or modulo by zero
> /usr/lib/python2.7/bdb.py(177)_set_stopinfo()
    176     def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
--> 177         self.stopframe = stopframe
    178         self.returnframe = returnframe

ipdb> whatis
*** SyntaxError: SyntaxError('unexpected EOF while parsing', ('<string>', 0, 0, ''))
ipdb> where
  /usr/lib/python2.7/bdb.py(43)reset()
     41         linecache.checkcache()
     42         self.botframe = None
---> 43         self._set_stopinfo(None, None)
     44 
     45     def trace_dispatch(self, frame, event, arg):

> /usr/lib/python2.7/bdb.py(177)_set_stopinfo()
    175 
    176     def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
--> 177         self.stopframe = stopframe
    178         self.returnframe = returnframe
    179         self.quitting = 0

The documentation for pdbis here: http://docs.python.org/2/library/pdb.html

+1
source

All Articles