Python自定义异常触发及捕获
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__函数的作用是打印对象时候,显示的字符串。

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

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: 自定义异常

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

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

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

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