gpt4 book ai didi

Python处理多个异常

转载 作者:太空狗 更新时间:2023-10-29 21:24:10 25 4
gpt4 key购买 nike

我想以某种方式处理特定异常,并一般记录所有其他异常。这是我的:

class MyCustomException(Exception): pass


try:
something()
except MyCustomException:
something_custom()
except Exception as e:
#all others
logging.error("{}".format(e))

问题是即使 MyCustomException 也会被记录,因为它继承自 Exception。我该怎么做才能避免这种情况?

最佳答案

您的代码中还发生了什么?

MyCustomException 应该在流程到达第二个 except 子句之前进行检查和处理

In [1]: def test():
...: try:
...: raise ValueError()
...: except ValueError:
...: print('valueerror')
...: except Exception:
...: print('exception')
...:

In [2]: test()
valueerror

In [3]: issubclass(ValueError,Exception)
Out[3]: True

关于Python处理多个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com