Pthon面向对象-异常处理
2024-09-06 04:30:23
Pthon面向对象-异常处理
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.异常概述
1>.错误(Error)
逻辑错误:
算法写错了,例如加法写成了减法。 笔误:
例如变量名写错了,语法错误等。 函数或类使用错误,其实这也属于逻辑错误。 总之,错误时可以避免的。
2>.异常(Exception)
Exception本意就是意外情况。 这有个前提,没有出现上面说的错误,也就是说程序写的没有问题,但是在某种情况下,会出现一些意外,导致程序无法正常的执行下去。 例如open函数操作一个文件,文件不村咋子,或者创建一个文件时已经存在了,或者访问一个网络文件,突然断网了,这就是异常,是个意外的情况。 异常不可能避免。
3>.错误和异常
在高级编程这语言中,一般都有错误和异常的概念,异常时可以捕获,并被处理的,但是错误是不能被捕获的。 一个健壮的程序,尽可能的避免错误,尽可能的避免错误,尽可能的捕获,处理各种异常。
4>.产生异常
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie """
raise语句显式的抛出异常,Python解释器自己检测到异常并引发它
"""
def foo():
print("before")
raise Exception("my exception") # raise主动抛出异常,程序会在异常抛出的地方中断执行,如果不捕获,就会提前结束程序(其实是终止当前线程的执行)
print("after") foo()
5>.异常的捕获
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie def foo():
try:
print("before")
c = 1 / 0 #想必大家都知道在运行改行代码会引发"除零异常"
print("after")
except: #我们可以指定捕获的异常类型,如果不写默认捕获所有异常。
print("error") print("catch the exception") foo() print("{0} 程序运行结束 {0}".format("*" * 20)) #以上代码执行结果如下:
before
error
catch the exception
******************** 程序运行结束 ********************
二.异常类及继承层次
1>.异常的祖先类(BaseException)
2>.通过"__subclasses__()"属性查看BaseException的子类
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie print(BaseException.__subclasses__()) print(Exception.__subclasses__()) print(RuntimeError.__subclasses__()) print(ArithmeticError.__subclasses__()) print(LookupError.__subclasses__()) print(OSError.__subclasses__()) #以上代码执行结果如下:
[<class 'Exception'>, <class 'GeneratorExit'>, <class 'SystemExit'>, <class 'KeyboardInterrupt'>]
[<class 'TypeError'>, <class 'StopAsyncIteration'>, <class 'StopIteration'>, <class 'ImportError'>, <class 'OSError'>, <class 'EOFError'>, <class 'RuntimeError'>, <class 'NameError'>, <class 'AttributeError'>, <class 'SyntaxError'>, <class 'LookupError'>, <class 'ValueError'>, <class 'AssertionError'>, <class 'ArithmeticError'>, <class 'SystemError'>, <class 'ReferenceError'>, <class 'MemoryError'>, <class 'BufferError'>, <class 'Warning'>, <class 'locale.Error'>]
[<class 'RecursionError'>, <class 'NotImplementedError'>, <class '_frozen_importlib._DeadlockError'>]
[<class 'FloatingPointError'>, <class 'OverflowError'>, <class 'ZeroDivisionError'>]
[<class 'IndexError'>, <class 'KeyError'>, <class 'encodings.CodecRegistryError'>]
[<class 'ConnectionError'>, <class 'BlockingIOError'>, <class 'ChildProcessError'>, <class 'FileExistsError'>, <class 'FileNotFoundError'>, <class 'IsADirectoryError'>, <class 'NotADirectoryError'>, <class 'InterruptedError'>, <class 'PermissionError'>, <class 'ProcessLookupError'>, <class 'TimeoutError'>, <class 'io.UnsupportedOperation'>]
三.自定义异常类
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie class MyException(Exception):
pass try:
raise MyException()
except MyException: #捕获自定义异常
print("catch the exception") #以上代码执行结果如下:
catch the exception
四.多种捕获
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie import sys """
捕获规则:
捕获是从上到下依次比较,如果匹配,则执行匹配的except语句块
如果被一个except语句捕获,其它except语句就不会再次捕获了
如果没有任何一个except语句捕获到这个异常,该异常向外抛出
如果"except:"称为缺省捕获,缺省捕获必须except捕获语句的最后。 捕获的原则:
从小到大,从具体到宽泛
""" class MyException(Exception):
pass try:
a = 1 / 0
raise MyException()
open("t")
sys.exit(1)
except ZeroDivisionError:
print("zero")
except ArithmeticError:
print("ari")
except MyException: #捕获自定义异常
print("catch the exception")
except Exception:
print("excption")
except: #缺省捕获
print("sys exit") #以上代码执行几个如下:
zero
五.as子句
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie class MyException(Exception):
def __init__(self,code,message):
self.code = code
self.message = message try:
"""
raise语句:
raise后要求应该是BaseException类的子类或实例,如果是类,将被无参实例化。
raise后上面都没有,表示抛出最近一个被激活的异常,如果没有被激活的异常,则抛出类型异常。这种方式很少用。
"""
raise MyException(200,"ok")
except MyException as e:
print("catch my exception: {} {}".format(e.code,e.message))
except Exception as e:
print("{}".format(e)) #以上代码执行几个如下:
catch my exception: 200 ok
六.finally子句
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie f = None try:
f = open("test.txt")
except FileNotFoundError as e:
print("{} {} {}".format(e.__class__,e.errno,e.strerror))
finally:
print("清理工作")
f.close()
七.else子句
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie try:
ret = 1 * 0
except ArithmeticError as e:
print(e)
else: #没有任何异常则执行
print("ok")
finally:
print("finally") #以上代码执行结果如下:
ok
finally
八.总结
1>.语法格式
try:
<语句> #运行别的代码
except <异常类>:
<语句> #捕获某种类型的异常
except <异常类> as <变量名>:
<语句> #捕获某种类的异常并获得对象
except:
<语句> #缺省捕获
else:
<语句> #如果没有异常发生才会执行
finally:
<语句> #退出try时总会执行
2>.try的工作原理
如果try中语句执行时发生异常,搜索except子句,并执行第一个匹配该异常的except子句。
如果try中语句执行发生异常,却没有匹配的except子句,异常将被递交到外层的try,如果外层不处理这个异常,异常将继续向外层传递。如果都不处理该异常,则会传递到最外层,如果还没有处理,就终止异常所在的线程。 如果在try执行时没有发生异常,如有else子句,可执行else子句中的语句。 无论try中是否发生异常,finally子句最终都会执行。
最新文章
- [整理]一个有关Latch(锁存器)的有趣问题
- Python打包成exe程序
- 修改mysql用户名密码 和 PHPmysqlAdmin对应密码修改
- 当应用程序不是以 UserInteractive 模式运行时显示模式对话框或窗体是无效操作
- Export Farm Solution wsp Files SharePoint 2007 and 2010
- mysql数据库常用语句
- 下拉菜单选择(jQuery实现)
- 将EXCEL中的列拼接成SQL insert插入语句
- JVM基础和调优(六)
- [DevExpress]图表开发工具类 ChartUtils
- AS3条件编译
- JavaScript一些常用方法一
- Redis的key过期处理策略
- Android TV开发总结(五)TV上屏幕适配总结
- 2019余姚培训游记+ZJOJD2划水记
- 报Error creating bean with name &#39;dataSource&#39; defined in class path resource 报错解决办法
- MidoNet 安装(Kilo RDO)(最老版)
- symmfony
- bzoj 3083
- m3u8文件下载合并的一种方法