20、Python相关-【异常处理】异常处理讲解(二)

文章目录

前言

1.自定义异常


前言

如果系统异常类型满足不了业务需求,那么可以自己定义异常类来处理。


1.自定义异常

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

  • 步骤:

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

    • 重写__str__方法输出异常信息

    • 编写异常处理方法处理异常

class CustomError(BaseException): #继承BaseException
    def __init__(self,msg):
        super().__init__()  #调用父类初始化
        self.msg = msg
        
    #重写__str__,输出异常信息
    def __str__(self):
        return self.msg
    
    #3.自定义异常处理方法
    def handle_exception(self):
        print('异常处理')
        
try:
    raise CustomError('自定义异常')
except CustomError as e:
    print(e)


总结

以上是对自定义异常的讲解!

 

关注公众号“软件测试技术联盟”,发送“测试资料”,免费获取全栈软件测试视频资料!!!

 

posted @ 2021-08-10 10:19  测开星辰  阅读(21)  评论(0编辑  收藏  举报