Proper way to declare custom exceptions in modern Python?

后端 未结 11 1635
栀梦
栀梦 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

    With modern Python Exceptions, you don't need to abuse .message, or override .__str__() or .__repr__() or any of it. If all you want is an informative message when your exception is raised, do this:

    class MyException(Exception):
        pass
    
    raise MyException("My hovercraft is full of eels")
    

    That will give a traceback ending with MyException: My hovercraft is full of eels.

    If you want more flexibility from the exception, you could pass a dictionary as the argument:

    raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"})
    

    However, to get at those details in an except block is a bit more complicated. The details are stored in the args attribute, which is a list. You would need to do something like this:

    try:
        raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"})
    except MyException as e:
        details = e.args[0]
        print(details["animal"])
    

    It is still possible to pass in multiple items to the exception and access them via tuple indexes, but this is highly discouraged (and was even intended for deprecation a while back). If you do need more than a single piece of information and the above method is not sufficient for you, then you should subclass Exception as described in the tutorial.

    class MyError(Exception):
        def __init__(self, message, animal):
            self.message = message
            self.animal = animal
        def __str__(self):
            return self.message
    

提交回复
热议问题