Thursday, August 3, 2023

Python Tips - Create A User-defined Exception

  

Scenario

Python provides a bunch of built-in exceptions such as FileNotFoundError, IOError, ConnectionError, ZeroDivisionError, IndexError and etc. However, they belong to system or application exceptions. In business operation, some patterns are not allowed to happen, for example, an account balance can’t be minus. When that pattern occurs, we can raise a particular business logic exception so that the program can catch it and process it and continue with grace. Hence, we can define a dedicated exception class in response to this case.


Example

Here we assume the exception class holds basic information, an error code and an error message. Of course, you can customize it according to your requirements. Both code and message are not modifiable, but the class must provide a means that an external object or method can use to get their values. 

The codes are shown below.

# Define BizException:
class BizException(Exception):
    __code = 'E0001'
    __message = 'A business logic exception'

    @property
    def code(self):
        return self.__code

    @property
    def message(self):
        return self.__message

    def getcode(self):
        return self.__code

    def getmessage(self):
        return self.__message

    def __str__(self):
        return self.__code + ': ' + self.__message


# Test BizException
if __name__ == '__main__':
    try:
        ex = BizException()
        raise ex
    except BizException as ex:
        print(type(ex))
        print(ex.code, ex.message)
        print(str(ex))


# Output:
<class 'bizexception.BizException'>
E0001 A business logic exception
E0001: A business logic exception

 


No comments:

Post a Comment

React - Makeover in React: W3Schools How To

When it comes to building a React app, I get used to searching for a UI library to build the front pages, a straightforward way to achieve f...