目录
Python异常信息的输出
捕获异常时,有 2 种方式可获得更多的异常信息,分别是:
- 使用 sys 模块中的 exc_info 方法;
- 使用 traceback 模块中的相关函数。
Python异常信息的输出exc_info方法
下面看一下输出异常信息的示例
# 定义除法函数
def divi(x,y):
try:
if x>y:
z=x/y
return z
except Exception as e:
print(e)
res=divi(6,2)
print(res)
res=divi(6,0)
print(res)
res=divi(6,"2")
print(res)
运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t32.py
3.0
division by zero
None
'>' not supported between instances of 'int' and 'str'
None
Process finished with exit code 0
上面程序,异常信息输出内容不完整。使用exc_info方法输出较完整信息,代码如下。
import sys
# 定义除法函数
def divi(x,y):
try:
if x>y:
z=x/y
return z
except Exception as e:
print(sys.exc_info())
res=divi(6,2)
print(res)
res=divi(6,0)
print(res)
res=divi(6,"2")
print(res)
运行结果(异常信息较完整)
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t32.py
3.0
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x0000023DE5814DC8>)
None
(<class 'TypeError'>, TypeError("'>' not supported between instances of 'int' and 'str'"), <traceback object at 0x0000023DE582BAC8>)
None
Process finished with exit code 0
Python异常信息的输出traceback 方法
import traceback
# 定义除法函数
def divi(x,y):
try:
if x>y:
z=x/y
return z
except Exception as e:
print(traceback.format_exc())
res=divi(6,2)
print(res)
res=divi(6,0)
print(res)
res=divi(6,"2")
print(res)
运行结果(有异常信息和出错位置的追踪)
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t32.py
3.0
Traceback (most recent call last):
File "E:/wkp01/p00/test01/atestpkg/t32.py", line 7, in divi
z=x/y
ZeroDivisionError: division by zero
None
Traceback (most recent call last):
File "E:/wkp01/p00/test01/atestpkg/t32.py", line 6, in divi
if x>y:
TypeError: '>' not supported between instances of 'int' and 'str'
None
Process finished with exit code 0
Python将异常信息输出到文件
traceback模块中的函数还可以将Python将异常信息输出到文件,示例代码如下。
import traceback
# 定义除法函数
def divi(x,y):
try:
if x>y:
z=x/y
return z
except Exception as e:
print(traceback.print_exc(file=open("log.txt","a")))
res=divi(6,2)
print(res)
res=divi(6,0)
print(res)
res=divi(6,"2")
print(res)
运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t32.py
3.0
None
None
None
None
Process finished with exit code 0
另外,生成的log.txt文件,内容如下。
Traceback (most recent call last):
File "E:/wkp01/p00/test01/atestpkg/t32.py", line 7, in divi
z=x/y
ZeroDivisionError: division by zero
Traceback (most recent call last):
File "E:/wkp01/p00/test01/atestpkg/t32.py", line 6, in divi
if x>y:
TypeError: '>' not supported between instances of 'int' and 'str'