def func(num1, num2):
try:
x = num1 * num2
y = num1 / num2
return x, y
except Exception as e:
print("错误信息:", e)
func(1, 0)
运行结果:
错误信息: division by zero
只能打印我们处理的结果或者将异常打印出来,不能直观的知道在哪个文件中的哪一行出错
Python解释器在打印堆栈跟踪时的行为:
import sys
def func1(num1, num2):
x = num1 * num2
y = num1 / num2
return x, y
def func2():
func1(1, 0)
if __name__ == '__main__':
try:
func2()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
print("exc_type:",exc_type)
print("exc_value:",exc_value)
print("exc_traceback:",exc_traceback)
运行结果:
exc_type:
exc_value: division by zero
exc_traceback:
sys.exc_info()获取了当前处理的exception的相关信息,并返回一个元组
元组的第一个数据是异常的类型,第二个返回值是异常的value值,第三个是traceback object
import sys
import traceback
def func1(num1, num2):
x = num1 * num2
y = num1 / num2
return x, y
def func2():
func1(1, 0)
if __name__ == '__main__':
try:
func2()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_tb(exc_traceback)
运行结果:
File "", line 15, in
func2()
File "", line 10, in func2
func1(1, 0)
File "", line 7, in func1
y = num1 / num2
说明:traceback.print_tb(tb, limit=None, file=None)
1.tb: 这个就是traceback object, 是我们通过sys.exc_info获取到的
2.limit: 这个是限制stack trace层级的,如果不设或者为None,就会打印所有层级的stack trace
3.file: 这个是设置打印的输出流的,可以为文件,也可以是stdout之类的file-like object。如果不设或为None,则输出到sys.stderr。
PS: 如果limit为正,则打印以limit来自traceback 对象tb的堆栈跟踪条目(从调用方的帧开始)。否则,打印最后一个abs(limit)条目。如果省略限制或无限制,则打印所有条目。如果文件被省略或无文件,则输出到sys.stderr;否则,它应该是一个打开的文件或类似文件的对象来接收输出。
import sys
import traceback
def func1(num1, num2):
x = num1 * num2
y = num1 / num2
return x, y
def func2():
func1(1, 0)
if __name__ == '__main__':
try:
func2()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, limit=None, file=sys.stdout)
运行结果:
Traceback (most recent call last):
File "", line 15, in
func2()
File "", line 10, in func2
func1(1, 0)
File "", line 7, in func1
y = num1 / num2
ZeroDivisionError: division by zero
说明:traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
1.前三个参数正好是sys.exc_info()返回的三个值
2.与print_tb相比,打印信息多了开头的"Traceback (most…)“信息以及最后一行的异常类型和value信息
3.还有一个不同是当异常为SyntaxError时,会有”^"来指示语法错误的位置
import traceback
def func(num1, num2):
try:
x = num1 * num2
y = num1 / num2
return x, y
except:
traceback.print_exc(file=open('traceback.txt','w+'))
func(1, 0)
运行结果(traceback.txt):
Traceback (most recent call last):
File "", line 7, in func
y = num1 / num2
ZeroDivisionError: division by zero
或者创建内存文件对象:
import traceback
import io
def func(num1, num2):
try:
x = num1 * num2
y = num1 / num2
return x, y
except:
fp = io.StringIO() # 创建内存文件对象
traceback.print_exc(file=fp)
message = fp.getvalue()
print(message)
func(1, 0)
运行结果:
Traceback (most recent call last):
File "", line 8, in func
y = num1 / num2
ZeroDivisionError: division by zero
PS:print_exc是简化版的print_exception, 由于exception type, value和traceback object都可以通过sys.exc_info()获取,因此print_exc()就自动执行exc_info()来帮助获取这三个参数。
所以traceback.print_exc(limit=None, file=None, chain=True)可将异常直接打印出来,同时可以将异常信息写入到文件中
import traceback
def func(num1, num2):
try:
x = num1 * num2
y = num1 / num2
return x, y
except:
print(traceback.format_exc())
func(1, 0)
运行结果:
Traceback (most recent call last):
File "", line 7, in func
y = num1 / num2
ZeroDivisionError: division by zero
PS:traceback.format_exc(limit=None, chain=True)返回的是一个字段串,效果与traceback.print_exc()一致,比如我们想通过logger将异常记录在log里,就可以使用format_exc