如何获取 Python 中引发的异常的名称?
例如,
try:
foo = bar
except Exception as exception:
name_of_exception = ???
assert name_of_exception == 'NameError'
print "Failed with exception [%s]" % name_of_exception
例如,我正在捕获多个(或全部)异常,并希望在错误消息中打印异常的名称。
最佳答案
这里有几种不同的方法来获取异常类的名称:
类型(异常).__name__
exception.__class__.__name__
exception.__class__.__qualname__
例如,
try:
foo = bar
except Exception as exception:
assert type(exception).__name__ == 'NameError'
assert exception.__class__.__name__ == 'NameError'
assert exception.__class__.__qualname__ == 'NameError'
关于python - 如何获取在 Python 中捕获的异常的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176602/