简体   繁体   中英

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

Every class that you create in Python implicitly derives from 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). This custom exception will successfully pass the isinstance(MyException, object) test, so it's still an 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:

class MyException:
    pass


raise MyException()

raise requires a few special C-level attributes to work correctly (notably these here ).

The only way to get these into your object in pure python is to subclass 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM