Section 10.12. Exceptions and the sys Module


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:

  • exc_type: exception class object

  • exc_value: (this) exception class instance object

  • exc_traceback: 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. All three will be phased out and eventually removed in a future version of Python.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net