< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204174054034005193195016053

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) exception class instance object

  • traceback object

The first two items we are familiar with: the actual exception class and this particular exception's instance (which is the same as the exception argument which we discussed in the previous section). The third item, a traceback object, is new. This object provides the execution context of where the exception occurred. It contains information such as the execution frame of the code that was running and the line number where the exception occurred.

In older versions of Python, these three values were available in the sys module as sys.exc_type, sys.exc_value, and sys.exc_traceback. Unfortunately, these three are global variables and not thread-safe. We recommend using sys.exc_info() instead.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.