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面向对象-异常处理的更多相关文章

  1. Pthon面向对象-补充知识

    Pthon面向对象-补充知识 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.tracemalloc 标准库tracemalloc,可以统计内存使用情况,通过下面的案例可以看出内 ...

  2. Pthon面向对象-特殊属性

    Pthon面向对象-特殊属性 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.   一.特殊属性 #!/usr/bin/env python #_*_conding:utf-8_*_ ...

  3. Java 面向对象异常处理,finally,覆盖时异常特点,package,import,包之间的访问(10)

    Java 面向对象异常处理, finally:final 关键字的用法参考http://www.cnblogs.com/itcqx/p/5541659.html 覆盖时异常特点,package,imp ...

  4. Java 面向对象 异常处理:RunTimeexception,try-catch,异常声明throws,自定义异常,throw和throws的区别,多异常处理(9)

    Java 面向对象 异常处理:RunTimeexception,try-catch,异常声明throws,自定义异常,throw和throws的区别,多异常处理(9)

  5. Python之旅Day7 面向对象&异常处理

    ########################################面向对象初识######################################### 面向对象简介 面向对象编 ...

  6. PHP面向对象——异常处理

    Error_reporting(0);  //在网站正式上线的时候不准他报任何错误.  错误级别为不允许报错 Exception 是所有异常的基类. 测试并捕捉一个错误的例子:  class mysq ...

  7. Pthon面向对象之基础

    命名空间 class Course: language = 'Chinese' def __init__(self,teacher,name,period,price): self.teacher = ...

  8. Python Learning

    这是自己之前整理的学习Python的资料,分享出来,希望能给别人一点帮助. Learning Plan Python是什么?- 对Python有基本的认识 版本区别 下载 安装 IDE 文件构造 Py ...

  9. 九天学会Java,第二天,算术运算

    算术运算 先回顾上次我们提到的编程特性 变量和数据类型,赋值和输出 算术运算 选择结构 循环结构 函数定义,函数调用 变量作用域 栈,程序运行的基石 面向对象 异常处理 语言提供的公用包 第一天我们讲 ...

随机推荐

  1. Python 工匠:使用数字与字符串的技巧学习笔记

    #Python 工匠:使用数字与字符串的技巧学习笔记#https://github.com/piglei/one-python-craftsman/blob/master/zh_CN/3-tips-o ...

  2. Laravel 登录后跳转回登录前浏览的页面

    一.经过 Auth 中间件检查后跳转至登录页面 也就是没有通过 auth 中间件的认证检查,被 auth 中间件拦截后跳转至登录页面.这种情况下,Laravel 默认会在用户登录成功后自动跳转回登录前 ...

  3. PageRank算法原理与Python实现

    一.什么是pagerank PageRank的Page可是认为是网页,表示网页排名,也可以认为是Larry Page(google 产品经理),因为他是这个算法的发明者之一,还是google CEO( ...

  4. JAVA中List对象去除重复值的方法

    JAVA中List对象去除重复值,大致分为两种情况,一种是List<String>.List<Integer>这类,直接根据List中的值进行去重,另一种是List<Us ...

  5. LeetCode 5274. Number of Ways to Stay in the Same Place After Some Steps - Java - DP

    题目链接:5274. 停在原地的方案数 You have a pointer at index 0 in an array of size arrLen. At each step, you can ...

  6. golang 之 go-micro

    在安装之前首先需要对go-micro有一定的了解 https://micro.mu/docs/cn/  go-micro中文文档 https://juejin.im/post/5cebafe6f265 ...

  7. 【题解】Luogu P5340 [TJOI2019]大中锋的游乐场

    原题传送门 没想到省选也会出这种题??! 实际就是一个带有限制的最短路 因为\(k<=10\),所以我们珂以暴力将每个点的权值分为[-k,k],为了方便我们珂以转化成[0,2k],将汉堡的权值记 ...

  8. arc079

    D. Decrease (Contestant ver.) 大意: 每次操作选一个最大数$-n$,其余数全$+1$. 要求构造一个序列$a$, 使得恰好$k$次操作后最大值不超过$n-1$. 只要让$ ...

  9. C++ 的多继承与虚继承

    C++之多继承与虚继承   1. 多继承 1.1 多继承概念 一个类有多个直接基类的继承关系称为多继承 多继承声明语法 class 派生类名 : 访问控制 基类名1, 访问控制 基类名2, ... { ...

  10. 西门子S7-300 设置IP、子网掩码

    =============================================== 2019/7/17_第1次修改                       ccb_warlock == ...