自定义异常

class CustomError(BaseException):

    def __init__(self,msg):
        super().__init__() #调用父类的初始化方法 BaseException
        self.msg = msg

    def __str__(self):
        self.handle_exception()
        return self.msg

    def handle_exception(self):
        print('异常的处理')


try:
    raise CustomError('自定义异常')
except CustomError as e:
    print(e)

自己定义的异常类必须继承BaseException或者Exception

步骤:

在自定义异常类的构造方法中,调用父类构造函数__init__

重写__str__方法输出异常信息

编写异常处理方法处理异常(可选)