Proper way to declare custom exceptions in modern Python?

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

    Maybe I missed the question, but why not:

    class MyException(Exception):
        pass
    

    Edit: to override something (or pass extra args), do this:

    class ValidationError(Exception):
        def __init__(self, message, errors):
    
            # Call the base class constructor with the parameters it needs
            super(ValidationError, self).__init__(message)
    
            # Now for your custom code...
            self.errors = errors
    

    That way you could pass dict of error messages to the second param, and get to it later with e.errors


    Python 3 Update: In Python 3+, you can use this slightly more compact use of super():

    class ValidationError(Exception):
        def __init__(self, message, errors):
    
            # Call the base class constructor with the parameters it needs
            super().__init__(message)
    
            # Now for your custom code...
            self.errors = errors
    

提交回复
热议问题