Obtaining Error Information
❘
253
➤
➤
traceback
: An object that describes the stack trace for an exception. Normally, you
won’t use this information directly unless you truly need
to obtain the stack trace
information, which can prove difficult. If you need stack trace information, consider
using the
traceback
module features instead (see the “Using the traceback Module”
section of this chapter for details).
➤
➤
sys.exc_clear()
: Clears the existing exceptions from the current thread.
After you call this
function,
sys.exc_info()
returns
None
for all three elements in the
tuple
.
The
sys.exc_info()
function isn’t
very hard to use, but you can’t really try it out by executing it
directly in the IronPython console. You need to place it within a
try...except
structure instead.
The following code shows a quick demonstration you can type directly into the console window.
try:
5/0
except:
type, value = sys.exc_info()[:2]
print type
print value
The example uses a simple division by zero to create an exception. As previously noted, you normally
need just the first two elements of the
tuple
,
which you can obtain using
sys.exc_info()[:2]
. When
you execute this code, you see the following output.
Attempted to divide by zero.
Some IronPython
sys
module functions affect only the interactive thread (which means they’re
safe to use in multithreaded applications because there is only one interactive thread in any given
session). You could use these functions to determine the current type, value, and
traceback
for an
exception, but only for the interactive session, which means these functions are completely useless
for your application. In most cases, you avoid using these three functions.
➤
sys.last_traceback()
➤
sys.last_type()
➤
➤
sys.last_value()
➤
➤
You could run into problems when working with some functions in the
sys
module. For example,
these three functions are global, which means they aren’t specific to the current thread and are
therefore, unsafe to use in a multithreaded application.
➤
sys.exc_type()
➤
sys.exc_value()
➤
➤
sys.exc_traceback()
➤
➤
Interestingly enough, these three functions are also listed as deprecated (outdated) in most Python
implementations (including IronPython). As with all IronPython modules, you also have access to
548592c12.indd 253
2/24/10 12:48:47 PM
www.finebook.ir