如何获取在Python中捕获的异常的名称? [英] How to get the name of an exception that was caught in Python?
本文介绍了如何获取在Python中捕获的异常的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取Python中引发的异常的名称?
How can I get the name of an exception that was raised in Python?
例如
try:
foo = bar
except Exception as exception:
name_of_exception = ???
assert name_of_exception == 'NameError'
print "Failed with exception [%s]" % name_of_exception
例如,我正在捕获多个(或所有)异常,并希望在错误消息中打印异常的名称.
For example, I am catching multiple (or all) exceptions, and want to print the name of the exception in an error message.
推荐答案
以下是获取异常类名称的几种不同方法:
Here are a few different ways to get the name of the class of the exception:
-
type(exception).__name__
-
exception.__class__.__name__
-
exception.__class__.__qualname__
type(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中捕获的异常的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文