如何获取在Python中捕获的异常的名称?(How to get name of exception that was caught in Python?)

编程入门 行业动态 更新时间:2024-10-22 16:36:35
如何获取在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_exception

For 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'

更多推荐

本文发布于:2023-08-02 02:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1368375.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   名称   Python   exception   caught

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!