Proper way to declare custom exceptions in modern Python?

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

    As of Python 3.8 (2018, https://docs.python.org/dev/whatsnew/3.8.html), the recommended method is still:

    class CustomExceptionName(Exception):
        """Exception raised when very uncommon things happen"""
        pass
    

    Please don't forget to document, why a custom exception is neccessary!

    If you need to, this is the way to go for exceptions with more data:

    class CustomExceptionName(Exception):
        """Still an exception raised when uncommon things happen"""
        def __init__(self, message, payload=None):
            self.message = message
            self.payload = payload # you could add more args
        def __str__(self):
            return str(self.message) # __str__() obviously expects a string to be returned, so make sure not to send any other data types
    

    and fetch them like:

    try:
        raise CustomExceptionName("Very bad mistake.", "Forgot upgrading from Python 1")
    except CustomExceptionName as error:
        print(str(error)) # Very bad mistake
        print("Detail: {}".format(error.payload)) # Detail: Forgot upgrading from Python 1
    

    payload=None is important to make it pickle-able. Before dumping it, you have to call error.__reduce__(). Loading will work as expected.

    You maybe should investigate in finding a solution using pythons return statement if you need much data to be transferred to some outer structure. This seems to be clearer/more pythonic to me. Advanced exceptions are heavily used in Java, which can sometimes be annoying, when using a framework and having to catch all possible errors.

提交回复
热议问题