1、打开Python开发工具IDLE,新建‘myexcept.py’文件,并写代码如下:
classmyException(Exception):
def__init__(self,error):
self.error=error
def__str__(self,*args,**kwargs):
returnself.error
这就是自定义定义的异常类,继承自Exception父类,有error字段,__str__函数的作用是打印对象时候,显示的字符串。
2、继续写代码,抛出异常,代码如下:
classmyException(Exception):
def__init__(self,error):
self.error=error
def__str__(self,*args,**kwargs):
returnself.error
raisemyException('自定义异常')
3、F5运行程序,在Shell中打印出异常:
Traceback(mostrecentcalllast):
File "C:/Users/123/AppData/Local/Programs/Python/Python36/myexcept.py", line 7, in <module>
raisemyException('自定义异常')
myException:自定义异常
4、下面做测试来捕获这个异常,代码如下;
classmyException(Exception):
def__init__(self,error):
self.error=error
def__str__(self,*args,**kwargs):
returnself.error
try:
a=0
b=1
ifa!=b:
raisemyException('自定义异常')
exceptmyExceptionase:
print(e)
5、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常
6、也可以直接用Exception来捕获,代码如下:
classmyException(Exception):
def__init__(self,error):
self.error=error
def__str__(self,*args,**kwargs):
returnself.error
try:
a=0
b=1
ifa!=b:
raisemyException('自定义异常')
exceptExceptionase:
print(e)
7、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常