10.12. Exceptions and the sys Module

An alternative way of obtaining exception information is by accessing the exc_info() function in the sys module. This function provides a 3-tuple of information, more than what we can achieve by simply using only the exception argument. Let us see what we get using sys.exc_info():

>>> try:
…       float('abc123')
… except:import sys
…       exc_tuple = sys.exc_info()
…
>>> print exc_tuple
(<class exceptions.ValueError at f9838>, <exceptions.ValueError instance at 122fa8>,
<traceback object at 10de18>)
>>>
>>> for eachItem in exc_tuple:
…       print eachItem
…
exceptions.ValueError
invalid literal for float(): abc123
<traceback object at 10de18>

What we get from sys.exc_info() in a tuple are:

  • exception class object

  • (this) ...

Get Core Python Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.