在 Python 中,异常对象可以是任何对象,经常看到很多代码是直接raise一个字符串出来。异常对象和异常栈是分开的。
python中用于处理异常栈的模块是traceback模块,它提供了print_exception、format_exception等输出异常栈等常用的工具函数。
import sys
import traceback
def func(a, b):
return a / b
if __name__ == '__main__':
try:
func(1, 0)
except Exception as e:
print "print exc"
traceback.print_exc(file=sys.stdout)
输出结果:
print exc
Traceback (most recent call last):
File "./teststacktrace.py", line 7, in <module>
func(1, 0)
File "./teststacktrace.py", line 2, in func
return a / b
其实traceback.print_exc()函数只是traceback.print_exception()函数的一个简写形式,而它们获取异常相关的数据都是通过sys.exc_info()函数得到的。
def func(a, b):
return a / b
if __name__ == '__main__':
import sys
import traceback
try:
func(1, 0)
except Exception as e:
print "print_exception()"
exc_type, exc_value, exc_tb = sys.exc_info()
print 'the exc type is:', exc_type
print 'the exc value is:', exc_value
print 'the exc tb is:', exc_tb
traceback.print_exception(exc_type, exc_value, exc_tb)
输出结果:
print_exception()
the exc type is: <type 'exceptions.ZeroDivisionError'>
the exc value is: integer division or modulo by zero
the exc tb is: <traceback object at 0x104e7d4d0>
Traceback (most recent call last):
File "./teststacktrace.py", line 7, in <module>
func(1, 0)
File "./teststacktrace.py", line 2, in func
return a / b
ZeroDivisionError: integer division or modulo by zero
sys.exc_info()返回的值是一个元组,其中第一个元素,exc_type是异常的对象类型,exc_value是异常的值,exc_tb是一个traceback对象,对象中包含出错的行数、位置等数据。然后通过print_exception函数对这些异常数据进行整理输出。
traceback模块提供了extract_tb函数来更加详细的解释traceback对象所包含的数据:
def func(a, b):
return a / b
if __name__ == '__main__':
import sys
import traceback
try:
func(1, 0)
except:
_, _, exc_tb = sys.exc_info()
for filename, linenum, funcname, source in traceback.extract_tb(exc_tb):
print "%-23s:%s '%s' in %s()" % (filename, linenum, source, funcname)
输出结果:
samchimac:tracebacktest samchi$ python ./teststacktrace.py
./teststacktrace.py :7 'func(1, 0)' in <module>()
./teststacktrace.py :2 'return a / b' in func()