如何获取在Python中捕获的异常的名称?(How to get name of exception that was caught in Python?)
如何获取在Python中提出的异常的名称?
例如,
try: foo = bar except Exception as exception: name_of_exception = ??? assert name_of_exception == 'NameError' print "Failed with exception [%s]" % name_of_exception例如,我捕获多个(或全部)异常,并且想要在错误消息中打印异常的名称。
How can I get the name of an exception that was raised in Python?
e.g.,
try: foo = bar except Exception as exception: name_of_exception = ??? assert name_of_exception == 'NameError' print "Failed with exception [%s]" % name_of_exceptionFor example, I am catching multiple (or all) exceptions, and want to print the name of the exception in an error message.
最满意答案
以下是获取异常名称的两种不同方法:
type(exception).__name__ exception.__class__.__name__例如,
try: foo = bar except Exception as exception: assert type(exception).__name__ == 'NameError' assert exception.__class__.__name__ == 'NameError'Here are two different ways to get the name of the exception:
type(exception).__name__ exception.__class__.__name__e.g.,
try: foo = bar except Exception as exception: assert type(exception).__name__ == 'NameError' assert exception.__class__.__name__ == 'NameError'更多推荐
发布评论