Python自定义异常触发及捕获

 时间:2024-10-15 08:45:33

1、打开Python开发工具IDLE,新建‘myexcept.py’文件,并写代码如下:class myException(Exception): def __init__(self,error): self.error = error def __str__(self,*args,**kwargs): return self.error这就是我们自定义定义的异常类,继承自Exception父类,有error字段,__str__函数的作用是打印对象时候,显示的字符串。

Python自定义异常触发及捕获

2、继续写代码,抛出异常,代码如下:class myException(Exception): def __init__(self,error): self.error = error def __str__(self,*args,**kwargs): return self.errorraise myException('自定义异常')

Python自定义异常触发及捕获

3、F5运行程序,在Shell中打印出异常:Traceback (most recent call last): File "C:/Users/123/AppData/Local/Programs/Python/Python36/myexcept.py", line 7, in <module> raise myException('自定义异常')myException: 自定义异常

Python自定义异常触发及捕获

4、下面做测试来捕获这个异常,代码如下;class myException(Exception): def __init__烫喇霰嘴(self,error): self.error = error def __str__(self,*args,**kwargs): return self.errortry: a=0 b=1 if a != b: raise myException('自定义异常')except myException as e: print (e)

Python自定义异常触发及捕获

5、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常

Python自定义异常触发及捕获

6、也可以直接用Exception来捕获,代码如下:class myException(Except坡纠课柩ion): def __init__(self,error): self.error = error def __str__(self,*args,**kwargs): return self.errortry: a=0 b=1 if a != b: raise myException('自定义异常')except Exception as e: print (e)

Python自定义异常触发及捕获

7、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常

Python自定义异常触发及捕获
  • 一加9r设置默认浏览器的方法
  • 方舟之旅装备怎么获得
  • Windows10 Insider Preview水印怎么去除!
  • win11系统在哪里安装显卡驱动
  • 热门搜索
    干鱼怎么做好吃 读书用英语怎么说 怎么隆鼻 电脑怎么备份 申请报告怎么写 久咳不愈怎么办 湖北人怎么样 暗网怎么进入 紧张怎么办 我的世界怎么做机器人