如何获取 Python 中引发的异常的名称?
例如,
try:
foo = bar
except Exception as exception:
name_of_exception = ???
assert name_of_exception == 'NameError'
print "Failed with exception [%s]" % name_of_exception
例如,我正在捕获多个(或全部)异常,并希望在错误消息中打印异常的名称。
except NameError:
)开始呢?
traceback
模块,它具有对异常和回溯进行一些很好的格式化的函数。
except
语句处理,但在每种情况下日志条目都非常相似。
以下是获取异常类名称的几种不同方法:
类型(异常).__name__ 异常.__class__.__name__ 异常.__class__.__qualname__
例如,
try:
foo = bar
except Exception as exception:
assert type(exception).__name__ == 'NameError'
assert exception.__class__.__name__ == 'NameError'
assert exception.__class__.__qualname__ == 'NameError'
如果您想要完全限定的类名(例如 sqlalchemy.exc.IntegrityError
而不仅仅是 IntegrityError
),您可以使用下面的函数,我从 MB's awesome answer 到另一个问题(我只是重命名了一些变量以适应我的口味):
def get_full_class_name(obj):
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + '.' + obj.__class__.__name__
例子:
try:
# <do something with sqlalchemy that angers the database>
except sqlalchemy.exc.SQLAlchemyError as e:
print(get_full_class_name(e))
# sqlalchemy.exc.IntegrityError
您也可以使用 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__
您可以使用一些格式化的字符串打印异常:
例子:
try:
#Code to execute
except Exception as err:
print(f"{type(err).__name__} was raised: {err}")
这行得通,但似乎必须有一种更简单、更直接的方法?
try:
foo = bar
except Exception as exception:
assert repr(exception) == '''NameError("name 'bar' is not defined",)'''
name = repr(exception).split('(')[0]
assert name == 'NameError'
except Exception as exception
替换为您要捕获的异常类型,即 except NameError as exception
。
raise socket.timeout
时,您只会得到名称:timeout
traceback(most recent call last) : ...
?