Pthon面向对象-异常处理
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子句最终都会执行。
Pthon面向对象-异常处理的更多相关文章
- Pthon面向对象-补充知识
Pthon面向对象-补充知识 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.tracemalloc 标准库tracemalloc,可以统计内存使用情况,通过下面的案例可以看出内 ...
- Pthon面向对象-特殊属性
Pthon面向对象-特殊属性 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.特殊属性 #!/usr/bin/env python #_*_conding:utf-8_*_ ...
- Java 面向对象异常处理,finally,覆盖时异常特点,package,import,包之间的访问(10)
Java 面向对象异常处理, finally:final 关键字的用法参考http://www.cnblogs.com/itcqx/p/5541659.html 覆盖时异常特点,package,imp ...
- Java 面向对象 异常处理:RunTimeexception,try-catch,异常声明throws,自定义异常,throw和throws的区别,多异常处理(9)
Java 面向对象 异常处理:RunTimeexception,try-catch,异常声明throws,自定义异常,throw和throws的区别,多异常处理(9)
- Python之旅Day7 面向对象&异常处理
########################################面向对象初识######################################### 面向对象简介 面向对象编 ...
- PHP面向对象——异常处理
Error_reporting(0); //在网站正式上线的时候不准他报任何错误. 错误级别为不允许报错 Exception 是所有异常的基类. 测试并捕捉一个错误的例子: class mysq ...
- Pthon面向对象之基础
命名空间 class Course: language = 'Chinese' def __init__(self,teacher,name,period,price): self.teacher = ...
- Python Learning
这是自己之前整理的学习Python的资料,分享出来,希望能给别人一点帮助. Learning Plan Python是什么?- 对Python有基本的认识 版本区别 下载 安装 IDE 文件构造 Py ...
- 九天学会Java,第二天,算术运算
算术运算 先回顾上次我们提到的编程特性 变量和数据类型,赋值和输出 算术运算 选择结构 循环结构 函数定义,函数调用 变量作用域 栈,程序运行的基石 面向对象 异常处理 语言提供的公用包 第一天我们讲 ...
随机推荐
- pytorch中使用cuda扩展
以下面这个例子作为教程,实现功能是element-wise add: (pytorch中想调用cuda模块,还是用另外使用C编写接口脚本) 第一步:cuda编程的源文件和头文件 // mathutil ...
- Linux磁盘空间查看、磁盘被未知资源耗尽
Linux系统中,当我们使用rm在Linux上删除了大文件,但是如果有进程打开了这个大文件,却没有关闭这个文件的句柄, 那么Linux内核还是不会释放这个文件的磁盘空间,最后造成磁盘空间占用100%, ...
- Docker应用容器化
Docker 的核心思想就是如何将应用整合到容器中,并且能在容器中实际运行. 将应用整合到容器中并且运行起来的这个过程,称为“容器化”(Containerizing),有时也叫作“Docker化”(D ...
- Ubuntu下重启mysql
启动mysql: 方式一:sudo /etc/init.d/mysql start 方式二:sudo service mysql start 停止mysql: 方式一:sudo /etc/init.d ...
- python3.5+tornado学习
python3.5的安装 python官网下载地址:https://www.python.org/ 自行下载最新版本 下载pip包或者easy_install 后缀为.gz格式 地址:https:// ...
- 基于C++ STL sort函数对c++ string 进行字符串的局部排序
Paypal笔试挂了,因为好久没有在leedcode之类的网上写代码,字符输入调了半天,时间都用光了.... Description: 有一个字符串,现在对其进行多次局部排序,例如str=" ...
- Jmeter在Http Rest接口中自动生成签名(Json格式请求参数)
第一步: 签名的java类生成jar包,导入到jmeter的lib目录下(依赖的第三方包也要导入) 第二步:编写jmeter脚本,这里使用BeanShell 进行签名串的生成,目录结构如下: Bean ...
- 【实战经验】--Xilinx--IPcore--PLL生成
用途: PLL用于产生自己想要的时钟,可以倍频有可以分频,通常倍频. 生成: 1.打开ISE—— Project —— New source,选择IP(CORE Generator & Arc ...
- python递归函数和河内塔问题
关于递归函数: 函数内部调用自身的函数. 以n阶乘为例: f(n) = n ! = 1 x 2 x 3 x 4 x...x(n-1)x(n) = n x (n-1) ! def factorial(n ...
- CF1109F Sasha and Algorithm of Silence's Sounds LCT、线段树
传送门 构成一棵树可以分成两个限制:图不成环.图的点数-边数=1. 我们考虑枚举右端点\(r\)计算所有可能的左端点\(l\)的答案.我们先考虑第一个限制:图不成环.注意到当\(r\)确定的时候,满足 ...