SoFunction
Updated on 2024-11-13

Python exception module traceback usage example analysis

This article example describes the Python exception module traceback usage. Shared for your reference, as follows:

The traceback module is used to trace the return information of an exception. The following example shows this.

import traceback
try:
  raise SyntaxError, "traceback test"
except:
  traceback.print_exc()

will output something like this on the console:

Traceback (most recent call last):
  File "H:", line 3, in <module>
    raise SyntaxError, "traceback test"
SyntaxError: traceback test

Similar to what the interpreter returns when you don't catch an exception.

You can also pass in a file and write the return information to the file, as follows.

import traceback
import StringIO
try:
  raise SyntaxError, "traceback test"
except:
  fp = ()  # Create in-memory file objects
  traceback.print_exc(file=fp)
  message = ()
  print message

The output on the console is the same as in the above example, and the traceback module also provides theextract_tbfunction to format the trace return information to get a list of error messages, as follows.

import traceback
import sys
def tracebacktest():
  raise SyntaxError, "traceback test"
try:
  tracebacktest()
except:
  info = sys.exc_info()
  for file, lineno, function, text in traceback.extract_tb(info[2]):
    print file, "line:", lineno, "in", function
    print text
  print "** %s: %s" % info[:2]

The console output is as follows.

H: line: 7 in <module>
tracebacktest()
H: line: 5 in tracebacktest
raise SyntaxError, "traceback test"
** <type ''>: traceback test

in which the system exit is called when the denominator is 0. The code is as follows.

#!/usr/bin/python
import sys
def division(a=1, b=1):
  if b==0:
     print 'b eq 0'
     (1)
  else:
     return a/b

in, withtry..exceptCatch the exception and thentraceback.print_exc()Print.

The code is as follows.

#!/usr/bin/python
import sys
import traceback
import test1
a=10
b=0
try:
  print (a,b)
except:
  print 'invoking division failed.'
  traceback.print_exc()
  (1)

Failed execution throws an exception.

$python

execution python-2.5.1/python (enodeb/linux)
b eq 0
invoking division failed.
Traceback (most recent call last):
 File "", line 10, in <module>
  (a,b)
 File "/home/fesu/", line 6, in division
  (1)
SystemExit: 1

For more Python related content, readers can check out this site's topic:Python introductory and advanced classic tutorials》、《Summary of Python string manipulation techniques》、《Python list (list) manipulation techniques summarized》、《Summary of Python coding manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tipsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.