如何获得在Python中引发的异常的名称?
例如,
try:
foo = bar
except Exception as exception:
name_of_exception = ???
assert name_of_exception == 'NameError'
print "Failed with exception [%s]" % name_of_exception
例如,我正在捕获多个(或所有)异常,并希望在错误消息中打印异常的名称。
发布于 2018-12-26 02:18:34
您也可以使用sys.exc_info()
。exc_info()
返回3个值:类型、值、回溯。在文档上:https://docs.python.org/3/library/sys.html#sys.exc_info
import sys
try:
foo = bar
except Exception:
exc_type, value, traceback = sys.exc_info()
assert exc_type.__name__ == 'NameError'
print "Failed with exception [%s]" % exc_type.__name__
发布于 2013-08-12 04:56:51
这是可行的,但似乎必须有一种更简单、更直接的方法?
try:
foo = bar
except Exception as exception:
assert repr(exception) == '''NameError("name 'bar' is not defined",)'''
name = repr(exception).split('(')[0]
assert name == 'NameError'
发布于 2021-07-14 01:06:54
您可以使用一些格式化字符串打印异常:
示例:
try:
#Code to execute
except Exception as err:
print(f"{type(err).__name__} was raised: {err}")
https://stackoverflow.com/questions/18176602
复制相似问题