关于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实现多线程采集的2个代码例子
Jul 07 Python
Python实现的ini文件操作类分享
Nov 20 Python
python开发之tkinter实现图形随鼠标移动的方法
Nov 11 Python
python 美化输出信息的实例
Oct 15 Python
浅谈pyqt5中信号与槽的认识
Feb 17 Python
python画图--输出指定像素点的颜色值方法
Jul 03 Python
Python如何筛选序列中的元素的方法实现
Jul 15 Python
详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件
Aug 23 Python
python库skimage给灰度图像染色的方法示例
Apr 27 Python
新手常见Python错误及异常解决处理方案
Jun 18 Python
python中time、datetime模块的使用
Dec 14 Python
浅谈pytorch中stack和cat的及to_tensor的坑
May 20 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 trim 去除空字符的定义与语法介绍
2010/05/31 PHP
ubuntu10.04配置 nginx+php-fpm模式的详解
2013/06/03 PHP
php object转数组示例
2014/01/15 PHP
PHP实现动态执行代码的方法
2016/03/25 PHP
JQuery EasyUI 日期控件如何控制日期选择区间
2014/05/05 Javascript
jQuery实现长按按钮触发事件的方法
2015/02/02 Javascript
jQuery操作JSON的CRUD用法实例
2015/02/25 Javascript
JS实现HTML表格排序功能
2016/08/05 Javascript
Javascript实现登录记住用户名和密码功能
2017/03/22 Javascript
微信小程序开发中的疑问解答汇总
2017/07/03 Javascript
AngularJS实现的JSONP跨域访问数据传输功能详解
2017/07/20 Javascript
浅谈箭头函数写法在ReactJs中的使用
2017/08/22 Javascript
浅谈Node.js CVE-2017-14849 漏洞分析(详细步骤)
2017/11/10 Javascript
微信小程序之多文件下载的简单封装示例
2018/01/29 Javascript
JS实现的文件拖拽上传功能示例
2018/05/21 Javascript
Element Dropdown下拉菜单的使用方法
2020/07/26 Javascript
javascript实现贪吃蛇小游戏
2020/07/28 Javascript
谈谈JavaScript令人迷惑的==与+
2020/08/31 Javascript
使用webpack5从0到1搭建一个react项目的实现步骤
2020/12/16 Javascript
[01:08:56]DOTA2-DPC中国联赛 正赛 Magma vs LBZS BO3 第一场 2月7日
2021/03/11 DOTA
Python获取当前页面内所有链接的四种方法对比分析
2017/08/19 Python
python实现数据写入excel表格
2018/03/25 Python
python使用turtle绘制分形树
2018/06/22 Python
Python如何使用函数做字典的值
2019/11/30 Python
GitHub上值得推荐的8个python 项目
2020/10/30 Python
CSS3属性background-size使用指南
2014/12/09 HTML / CSS
HTML5中实现拖放效果无须借助javascript
2012/12/26 HTML / CSS
html5 css3网站菜单实现代码
2013/12/23 HTML / CSS
墨尔本复古时尚品牌:Dangerfield
2018/12/12 全球购物
乌克兰电子和家用电器商店:Foxtrot
2019/07/23 全球购物
Lookfantastic俄罗斯:欧洲在线化妆品零售商
2019/08/06 全球购物
英国鞋网:Rubber Sole
2020/03/03 全球购物
旅游管理实习自我鉴定
2013/09/29 职场文书
校本教研活动总结
2014/07/01 职场文书
光棍节联谊晚会活动策划书
2014/10/10 职场文书
如何用Python搭建gRPC服务
2021/06/30 Python