pythonexceptiontry-catchread-eval-print-loop

How to get the last exception object after an error is raised at a Python prompt?


When debugging Python code at the interactive prompt (REPL), often I'll write some code which raises an exception, but I haven't wrapped it in a try/except, so once the error is raised, I've forever lost the exception object.

Often the traceback and error message Python prints out isn't enough. For example, when fetching a URL, the server might return a 40x error, and you need the content of the response via error.read() ... but you haven't got the error object anymore. For example:

>>> import urllib2
>>> f = urllib2.urlopen('http://example.com/api/?foo=bad-query-string')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
urllib2.HTTPError: HTTP Error 400: Bad Request

Drat, what did the body of the response say? It probably had valuable error information in it...

I realize it's usually easy to re-run your code wrapped in a try/except, but that's not ideal. I also realize that in this specific case if I were using the requests library (which doesn't raise for HTTP errors), I wouldn't have this problem ... but I'm really wondering if there's a more general way to get the last exception object at a Python prompt in these cases.


Solution

  • The sys module provides some functions for post-hoc examining of exceptions: sys.last_type, sys.last_value, and sys.last_traceback.

    sys.last_value is the one you're looking for.