gpt4 book ai didi

python-3.x - 从 BaseException 与 Exception 继承

转载 作者:行者123 更新时间:2023-12-04 12:24:35 25 4
gpt4 key购买 nike

我知道 Exception 和有什么区别和 BaseExceptionPython .我想知道什么是好的做法和更多的 Pythonic:
我的异常是否应该从 BaseException 继承或 Exception ?

最佳答案

默认情况下,所有用户定义的异常都应该从 Exception 继承。 .这是 recommended in the documentation :

exception Exception

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.



这也是 recommend by and motivated in PEP 8 :

Derive exceptions from Exception rather than BaseException. Direct inheritance from BaseException is reserved for exceptions where catching them is almost always the wrong thing to do.



通常,源自 Exception 的异常旨在由常规代码处理。相比之下,直接源自 BaseException 的异常与特殊情况有关;像正常异常一样处理它们会导致意外行为。这就是为什么惯用的“捕获所有”处理程序只处理 Exception :
def retry(func):
while True:
try:
return func()
except Exception as err:
print(f"retrying after {type(err)}: {err}")

直接从 BaseException 继承的内置异常目前是 KeyboardInterrupt , SystemExit , 和 GeneratorExit与程序、线程或生成器/协程的关闭相关联。不正确地处理它们将阻止正常关闭。

请注意,虽然默认值应该是继承自 Exception ,从 BaseException继承就可以了如果有充分的理由这样做。例如, asyncio.CancelledError 也继承自 BaseException因为它代表了 asyncio 的关闭的线程等价物,任务。

关于python-3.x - 从 BaseException 与 Exception 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60745841/

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