Proper way to declare custom exceptions in modern Python?

后端 未结 11 1864
栀梦
栀梦 2020-11-22 08:04

What\'s the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instan

11条回答
  •  一个人的身影
    2020-11-22 08:31

    See a very good article "The definitive guide to Python exceptions". The basic principles are:

    • Always inherit from (at least) Exception.
    • Always call BaseException.__init__ with only one argument.
    • When building a library, define a base class inheriting from Exception.
    • Provide details about the error.
    • Inherit from builtin exceptions types when it makes sense.

    There is also information on organizing (in modules) and wrapping exceptions, I recommend to read the guide.

提交回复
热议问题