简体   繁体   English

为什么需要从 BaseException 派生自定义异常?

[英]Why do you need to derive your custom exception from BaseException?

Every class that you create in Python implicitly derives from object .您在 Python 中创建的每个 class 都隐式派生自object To create a new error class, you must derive it from BaseException or one of its child classes (usually, Exception is used for this purpose).要创建新错误 class,您必须从BaseException或其子类之一派生它(通常,为此目的使用Exception )。 This custom exception will successfully pass the isinstance(MyException, object) test, so it's still an object .此自定义异常将成功通过isinstance(MyException, object)测试,因此它仍然是object But I wonder, what's the reason this restraint was implemented?但我想知道,实施这种限制的原因是什么? Why do we need to derive from BaseException or its descendants instead of doing like this:为什么我们需要从BaseException或其后代派生而不是这样做:

class MyException:
    pass


raise MyException()

raise requires a few special C-level attributes to work correctly (notably these here ). raise需要一些特殊的 C 级属性才能正常工作(尤其是这里的这些)。

The only way to get these into your object in pure python is to subclass BaseException .在纯 python 中将这些放入 object 的唯一方法是BaseException Because of this, the python devs simply decided that every raisable object, even if defined in a C module should inherit from BaseException to make the checks easy.正因为如此,python 开发人员简单地决定每个可提升的 object,即使在 C 模块中定义,也应该从BaseException继承以简化检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么建议在Python中派生Exception而不是BaseException类? - Why is it recommended to derive from Exception instead of BaseException class in Python? 异常必须从 BaseException 派生 - Exceptions must derive from BaseException 错误异常必须从 BaseException 派生,即使它确实存在(Python 2.7) - Error exception must derive from BaseException even when it does (Python 2.7) 失败:异常必须从 BaseException 派生 - failed: exceptions must derive from BaseException TypeError:异常必须从 BaseException 派生 - TypeError: exceptions must derive from BaseException Flask / Python API:TypeError:异常必须从 BaseException 派生 - Flask / Python API : TypeError: exceptions must derive from BaseException SystemExit异常不视为源自BaseException - SystemExit exception not seen as derived from BaseException Pytest & 自定义异常:TypeError:异常必须从 BaseException 派生,而不是 class 'module' - Pytest & custom exception : TypeError: exceptions must be derived from BaseException, not class 'module' 为什么我们应该使用Exception作为超类,为什么不使用BaseException - why should we use Exception as a superclass, why not BaseException 我得到“TypeError:异常必须从BaseException派生”,即使我确实定义了它 - I get “TypeError: exceptions must derive from BaseException” even though I did define it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM