try:
...
except Exception as error:
...
获取异常对象所属的类的名称
try:
function()
except Exception as error:
print 'type is:', error.__class__.__name__
给出异常信息,不包括异常信息的类型,如1/0的异常信息
'integer division or modulo by zero'
给出较全的异常信息,包括异常信息的类型,如1/0的异常信息
"ZeroDivisionError('integer division or modulo by zero',)"
需要导入traceback模块,此时获取的信息最全,与python命令行运行程序出现错误信息一致。
traceback.print_exc([limit[, file]])
import traceback
import sys
try:
int(a)
except Exception as error:
print('str(Exception):{}'.format(str(Exception)))
print('str(e):{}'.format(str(error)))
print('error.__class__.__name__:{}'.format(error.__class__.__name__))
print('repr(e):{}'.format(repr(error)))
print('traceback.print_exc():')
traceback.print_exc(file=sys.stdout)
print('traceback.format_exc():{}'.format(traceback.format_exc())) #字符串
输出结果:
str(Exception):<class 'Exception'>
str(e):name 'a' is not defined
error.__class__.__name__:NameError
repr(e):NameError("name 'a' is not defined")
traceback.print_exc():
Traceback (most recent call last):
File "/home/hkx303/Documents/CI/robottelo/robottelo/tests/foreman/virtwho/my_test.py", line 4, in <module>
int(a)
NameError: name 'a' is not defined
traceback.format_exc():Traceback (most recent call last):
File "/home/hkx303/Documents/CI/robottelo/robottelo/tests/foreman/virtwho/my_test.py", line 4, in <module>
int(a)
NameError: name 'a' is not defined