Python自定义异常触发及捕获

2025-05-14 06:34:07

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自定义异常触发及捕获
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢