Python Custom Exception Class

July 4, 2019
class CustomException(Exception):
    def __init__(self, code, msg=None): # msg=None as hack for pickle issue

        self.code = code
        self.msg = msg
        message = f"[{self.code}] {self.msg}"

        # Python 2.x
        # super(CustomException, self).__init__(message)
        super().__init__(message)

Usage

raise CustomException(code=100, msg="Test")

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.