关于Python中异常(Exception)的汇总


Posted in Python onJanuary 18, 2017

前言

Exception类是常用的异常类,该类包括StandardError,StopIteration, GeneratorExit, Warning等异常类。python中的异常使用继承结构创建,可以在异常处理程序中捕获基类异常,也可以捕获各种子类异常,python中使用try...except语句捕获异常,异常子句定义在try子句后面。

Python中的异常处理

异常处理的语句结构

try:
 <statements>  #运行try语句块,并试图捕获异常
except <name1>:
 <statements>  #如果name1异常发现,那么执行该语句块。
except (name2, name3):
 <statements>  #如果元组内的任意异常发生,那么捕获它
except <name4> as <variable>:
 <statements>  #如果name4异常发生,那么进入该语句块,并把异常实例命名为variable
except:
 <statements>  #发生了以上所有列出的异常之外的异常
else:
<statements>   #如果没有异常发生,那么执行该语句块
finally:
 <statement>   #无论是否有异常发生,均会执行该语句块。

说明

  • else和finally是可选的,可能会有0个或多个except,但是,如果出现一个else的话,必须有至少一个except。
  • 不管你如何指定异常,异常总是通过实例对象来识别,并且大多数时候在任意给定的时刻激活。一旦异常在程序中某处由一条except子句捕获,它就死掉了,除非由另一个raise语句或错误重新引发它。

raise语句

raise语句用来手动抛出一个异常,有下面几种调用格式:

  • raise #可以在raise语句之前创建该实例或者在raise语句中创建。
  • raise #Python会隐式地创建类的实例
  • raise name(value) #抛出异常的同时,提供额外信息value
  • raise # 把最近一次产生的异常重新抛出来
  • raise exception from E

例如:

抛出带有额外信息的ValueError: raise ValueError('we can only accept positive values')

当使用from的时候,第二个表达式指定了另一个异常类或实例,它会附加到引发异常的__cause__属性。如果引发的异常没有捕获,Python把异常也作为标准出错消息的一部分打印出来:

比如下面的代码:

try:
 1/0
except Exception as E:
 raise TypeError('bad input') from E

执行的结果如下:

Traceback (most recent call last):
 File "hh.py", line 2, in <module>
 1/0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "hh.py", line 4, in <module>
 raise TypeError('bad input') from E
TypeError: bad input

assert语句

assert主要用来做断言,通常用在单元测试中较多,到时候再做介绍。

with...as语句

with语句支持更丰富的基于对象的协议,可以为代码块定义支持进入和离开动作。

with语句对应的环境管理协议要求如下:

  • 环境管理器必须有__enter____exit__方法。

       __enter__方法会在初始化的时候运行,如果存在ass子在, __enter__函数的返回值会赋值给as子句中的变量,否则,直接丢弃。

       代码块中嵌套的代码会执行。

       如果with代码块引发异常, __exit__(type,value,traceback)方法就会被调用(带有异常细节)。这些也是由 sys.exc_info返回的相同值.如果此方法返回值为假,则异常会重新引发。否则,异常会终止。正常 情况下异常是应该被重新引发,这样的话才能传递到with语句之外。

       如果with代码块没有引发异常, __exit__方法依然会被调用,其type、value以及traceback参数都会以None传递。

下面为一个简单的自定义的上下文管理类。

class Block:
 def __enter__(self):
  print('entering to the block')
  return self
 
 def prt(self, args):
  print('this is the block we do %s' % args)

 def __exit__(self,exc_type, exc_value, exc_tb):
  if exc_type is None:
   print('exit normally without exception')
  else:
   print('found exception: %s, and detailed info is %s' % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt('actual work!')
 raise ValueError('wrong')

如果注销到上面的raise语句,那么会正常退出。

在没有注销掉该raise语句的情况下,运行结果如下:

entering to the block
this is the block we do actual work!
found exception: <class 'ValueError'>, and detailed info is wrong
Traceback (most recent call last):
 File "hh.py", line 18, in <module>
 raise ValueError('wrong')
ValueError: wrong

异常处理器

如果发生异常,那么通过调用sys.exc_info()函数,可以返回包含3个元素的元组。 第一个元素就是引发异常类,而第二个是实际引发的实例,第三个元素traceback对象,代表异常最初发生时调用的堆栈。如果一切正常,那么会返回3个None。

Python的Builtins模块中定义的Exception

|Exception Name|Description|
|BaseException|Root class for all exceptions|
| SystemExit|Request termination of Python interpreter|
|KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|Exception|Root class for regular exceptions|
| StopIteration|Iteration has no further values|
| GeneratorExit|Exception sent to generator to tell it to quit|
| SystemExit|Request termination of Python interpreter|
| StandardError|Base class for all standard built-in exceptions|
|  ArithmeticError|Base class for all numeric calculation errors|
|   FloatingPointError|Error in floating point calculation|
|   OverflowError|Calculation exceeded maximum limit for numerical type|
|   ZeroDivisionError|Division (or modulus) by zero error (all numeric types)|
|  AssertionError|Failure of assert statement|
|  AttributeError|No such object attribute|
|  EOFError|End-of-file marker reached without input from built-in|
|  EnvironmentError|Base class for operating system environment errors|
|   IOError|Failure of input/output operation|
|   OSError|Operating system error|
|    WindowsError|MS Windows system call failure|
|    ImportError|Failure to import module or object|
|    KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|   LookupError|Base class for invalid data lookup errors|
|    IndexError|No such index in sequence|
|    KeyError|No such key in mapping|
|   MemoryError|Out-of-memory error (non-fatal to Python interpreter)|
|   NameError|Undeclared/uninitialized object(non-attribute)|
|    UnboundLocalError|Access of an uninitialized local variable|
|   ReferenceError|Weak reference tried to access a garbage collected object|
|   RuntimeError|Generic default error during execution|
|    NotImplementedError|Unimplemented method|
|   SyntaxError|Error in Python syntax|
|    IndentationError|Improper indentation|
|     TabErrorg|Improper mixture of TABs and spaces|
|   SystemError|Generic interpreter system error|
|   TypeError|Invalid operation for type|
|   ValueError|Invalid argument given|
|    UnicodeError|Unicode-related error|
|     UnicodeDecodeError|Unicode error during decoding|
|     UnicodeEncodeError|Unicode error during encoding|
|     UnicodeTranslate Error|Unicode error during translation|
|  Warning|Root class for all warnings|
|   DeprecationWarning|Warning about deprecated features|
|   FutureWarning|Warning about constructs that will change semantically in the future|
|   OverflowWarning|Old warning for auto-long upgrade|
|   PendingDeprecation Warning|Warning about features that will be deprecated in the future|
|   RuntimeWarning|Warning about dubious runtime behavior|
|   SyntaxWarning|Warning about dubious syntax|
|   UserWarning|Warning generated by user code|

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

Python 相关文章推荐
使用Python来编写HTTP服务器的超级指南
Feb 18 Python
Python的Django应用程序解决AJAX跨域访问问题的方法
May 31 Python
Python Socket编程详细介绍
Mar 23 Python
Python简单网络编程示例【客户端与服务端】
May 26 Python
Python中Numpy包的安装与使用方法简明教程
Jul 03 Python
Sanic框架路由用法实例分析
Jul 16 Python
Python实现将数据写入netCDF4中的方法示例
Aug 30 Python
Python字典中的键映射多个值的方法(列表或者集合)
Oct 17 Python
对Python中for复合语句的使用示例讲解
Nov 01 Python
Python Django中的STATIC_URL 设置和使用方式
Mar 27 Python
python读取excel进行遍历/xlrd模块操作
Jul 12 Python
Django serializer优化类视图的实现示例
Jul 16 Python
python:socket传输大文件示例
Jan 18 #Python
详解使用pymysql在python中对mysql的增删改查操作(综合)
Jan 18 #Python
python实现下载整个ftp目录的方法
Jan 17 #Python
ansible作为python模块库使用的方法实例
Jan 17 #Python
python 基础教程之Map使用方法
Jan 17 #Python
Python获取某一天是星期几的方法示例
Jan 17 #Python
Python正则表达式匹配中文用法示例
Jan 17 #Python
You might like
PHP学习之PHP运算符
2006/10/09 PHP
初品cakephp 入门基础
2012/02/16 PHP
ThinkPHP项目分组配置方法分析
2016/03/23 PHP
ExtJS 工具栏 分页事件参数
2010/03/05 Javascript
实现web打印的各种方法介绍及实现代码
2013/01/09 Javascript
js实现两个值相加alert出来精确到指定位
2013/09/25 Javascript
关于onchange事件在IE和FF下的表现及解决方法
2014/03/08 Javascript
javascript快速排序算法详解
2014/09/17 Javascript
javascript数组去重方法汇总
2015/04/23 Javascript
Bootstrap每天必学之导航条
2015/11/27 Javascript
多种JQuery循环滚动文字图片效果代码
2020/06/23 Javascript
ReactNative 之FlatList使用及踩坑封装总结
2017/11/29 Javascript
如何利用 JS 脚本实现网页全自动秒杀抢购功能
2020/10/12 Javascript
[46:09]2014 DOTA2华西杯精英邀请赛 5 25 LGD VS VG第三场
2014/05/26 DOTA
python实现监控windows服务并自动启动服务示例
2014/04/17 Python
Python实现多并发访问网站功能示例
2017/06/19 Python
python利用插值法对折线进行平滑曲线处理
2018/12/25 Python
应用OpenCV和Python进行SIFT算法的实现详解
2019/08/21 Python
Python列表元素常见操作简单示例
2019/10/25 Python
opencv3/C++图像像素操作详解
2019/12/10 Python
Keras模型转成tensorflow的.pb操作
2020/07/06 Python
CSS3属性使网站设计增强同时不消弱可用性
2009/08/29 HTML / CSS
探讨HTML5移动开发的几大特性(必看)
2015/12/30 HTML / CSS
公司业务主管岗位职责
2013/12/07 职场文书
食品厂厂长岗位职责
2014/01/30 职场文书
法定代表人授权委托书范本
2014/10/07 职场文书
群众路线剖析材料范文
2014/10/09 职场文书
毕业论文指导教师评语
2014/12/30 职场文书
店铺转让协议书
2015/01/29 职场文书
2015年绩效考核工作总结
2015/05/23 职场文书
初中语文教师研修日志
2015/11/13 职场文书
幼儿园音乐教学反思
2016/02/18 职场文书
2016年“我们的节日·清明节”活动总结
2016/04/01 职场文书
导游词之井冈山
2019/11/20 职场文书
SQL实现LeetCode(197.上升温度)
2021/08/07 MySQL
索尼ICF-5900W收音机测评
2022/04/24 无线电