Example 2-18 shows that the Traceback module allows you to print unusual trace return (traceback) information in your program, similar to what the interpreter did when the exception was not caught. As shown in Example 2-18. 2.11.0.1. Example 2-18. Print trace return information using the Traceback module file:traceback-example-1.py # note! Import
Example 2-18 shows that the Traceback module allows you to print unusual trace return (traceback) information in your program, similar to what the interpreter did when the exception was not caught. As shown in Example 2-18. 2.11.0.1. Example 2-18. Print trace return information using the Traceback module
file:traceback-example-1.py
# note! Importing the Traceback module messes up the
# exception state, so your better do ' here and '
# in the exception handler
Attention! The import Traceback clears the exception state, so
# It's better not to import the module in exception handling code
Import Traceback
Try
Raise SyntaxError, "example"
Except
Traceback.print_exc ()
Traceback (innermost last):
File "traceback-example-1.py", line 7, in?
Syntaxerror:example
Example 2-19 uses the Stringio module to place trace return information in a string. 2.11.0.2. Example 2-19. Use the Traceback module to copy trace return information to a string
file:traceback-example-2.py
Import Traceback
Import Stringio
Try
Raise IOError, "an I/O error occurred"
Except
fp = Stringio.stringio ()
Traceback.print_exc (FILE=FP)
message = Fp.getvalue ()
Print "failure! The error is: ", repr (message)
failure! The error was: ' Traceback (innermost last):/012 File
"Traceback-example-2.py", line 5, in?/012ioerror:an I/O error
occurred/012 '
You can use the EXTRACT_TB function to format trace return information and get a list of error messages, as shown in Example 2-20. 2.11.0.3. Example 2-20. Encoding traceback objects using Traceback module modules
file:traceback-example-3.py
Import traceback
Import sys
def function ():
Raise IOError, " An I/O error occurred "
Try:
function ()
except:
info = sys.exc_info ()
for file, Lineno, function, text in TRACEBACK.EXTRACT_TB (info[2]):
Print file, ' line ', Lineno, ' in ', function
Print ' => ', repr (text)
Print * * *%s:%s '% info[:2]
traceback-example-3.py line 8 in?
=> ' Fun Ction () '
traceback-example-3.py line 5 in function
=> ' raise IOError, ' an I/O error occurred '
* * exception S.ioerror:an I/O error occurred