Proper way to declare custom exceptions in modern Python?

后端 未结 11 1859
栀梦
栀梦 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:18

    A really simple approach:

    class CustomError(Exception):
        pass
    
    raise CustomError("Hmm, seems like this was custom coded...")
    

    Or, have the error raise without printing __main__ (may look cleaner and neater):

    class CustomError(Exception):
        __module__ = Exception.__module__
    
    raise CustomError("Improved CustomError!")
    

提交回复
热议问题