如何获取 Python 中引发的异常的名称?
例如,
try: foo = bar except Exception as exception: name_of_exception = ??? assert name_of_exception == 'NameError' print "Failed with exception [%s]" % name_of_exception
例如,我正在捕获多个(或全部)异常,并希望在错误消息中打印异常的名称。
以下是获取异常类名称的几种不同方法:
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'