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 zeroThe 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 selfdef 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 Falsewith 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标准异常

异常名称 描述
BaseException 所有异常的基类
SystemExit 解释器请求退出
KeyboardInterrupt 用户中断执行(通常是输入^C)
Exception 常规错误的基类
StopIteration 迭代器没有更多的值
GeneratorExit 生成器(generator)发生异常来通知退出
StandardError 所有的内建标准异常的基类
ArithmeticError 所有数值计算错误的基类
FloatingPointError 浮点计算错误
OverflowError 数值运算超出最大限制
ZeroDivisionError 除(或取模)零 (所有数据类型)
AssertionError 断言语句失败
AttributeError 对象没有这个属性
EOFError 没有内建输入,到达EOF 标记
EnvironmentError 操作系统错误的基类
IOError 输入/输出操作失败
OSError 操作系统错误
WindowsError 系统调用失败
ImportError 导入模块/对象失败
LookupError 无效数据查询的基类
IndexError 序列中没有此索引(index)
KeyError 映射中没有这个键
MemoryError 内存溢出错误(对于Python 解释器不是致命的)
NameError 未声明/初始化对象 (没有属性)
UnboundLocalError 访问未初始化的本地变量
ReferenceError 弱引用(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError 一般的运行时错误
NotImplementedError 尚未实现的方法
SyntaxError Python 语法错误
IndentationError 缩进错误
TabError Tab 和空格混用
SystemError 一般的解释器系统错误
TypeError 对类型无效的操作
ValueError 传入无效的参数
UnicodeError Unicode 相关的错误
UnicodeDecodeError Unicode 解码时的错误
UnicodeEncodeError Unicode 编码时错误
UnicodeTranslateError Unicode 转换时错误
Warning 警告的基类
DeprecationWarning 关于被弃用的特征的警告
FutureWarning 关于构造将来语义会有改变的警告
OverflowWarning 旧的关于自动提升为长整型(long)的警告
PendingDeprecationWarning 关于特性将会被废弃的警告
RuntimeWarning 可疑的运行时行为(runtime behavior)的警告
SyntaxWarning 可疑的语法的警告
UserWarning 用户代码生成的警告

转载自:http://blog.csdn.net/vickey1018/article/details/51075277
   http://www.runoob.com/python/python-exceptions.html

Exception 异常相关推荐

  1. 解决“The type initializer for‘Oracle.DataAccess.Client.OracleConnection‘ threw an exception ”异常

    解决"The type initializer for'Oracle.DataAccess.Client.OracleConnection' threw an exception " ...

  2. Interrupted Exception异常可能没你想的那么简单!

    摘要: 当我们在调用Java对象的wait()方法或者线程的sleep()方法时,需要捕获并处理InterruptedException异常.如果我们对InterruptedException异常处理 ...

  3. java 异常 中英文_史上最全的Java中所有Exception异常中英文对照

    Java中所有Exception异常中英文对照AclNotFoundException, 如果对不存在的访问控制列表进行访问,则会 ArithmeticException 算数异常 ArrayInde ...

  4. python读取日志错误信息_使用Python将Exception异常错误堆栈信息写入日志文件

    假设需要把发生异常错误的信息写入到log.txt日志文件中去: import traceback import logging logging.basicConfig(filename='log.tx ...

  5. 最常见到的runtime exception 异常

    最常见到的runtime exception 异常 参考文章: (1)最常见到的runtime exception 异常 (2)https://www.cnblogs.com/jack4738/p/6 ...

  6. 自定义Exception异常

    自定义Exception异常 参考文章: (1)自定义Exception异常 (2)https://www.cnblogs.com/aeolian/p/10449506.html 备忘一下.

  7. terminate called without an active exception异常

    terminate called without an active exception异常 参考文章: (1)terminate called without an active exception ...

  8. .net core linux环境下导出到excel报The type initializer for ‘Gdip‘ threw an exception.异常

    .net core linux环境下导出到excel报The type initializer for 'Gdip' threw an exception.异常 一.安装一下包: yum -y ins ...

  9. .NET Core----Docker The type initializer for ‘Gdip‘ threw an exception异常

    .NET Core----Docker The type initializer for 'Gdip' threw an exception异常 参考文章: (1).NET Core----Docke ...

  10. .net Core 在 CentOS7下,报The type initializer for ‘Gdip‘ threw an exception.异常

    .net Core 在 CentOS7下,报The type initializer for 'Gdip' threw an exception.异常 参考文章: (1).net Core 在 Cen ...

最新文章

  1. 1. CVPR2021-Papers-with-Code-Demo(CVPR2021论文下载)
  2. 捕获Camera并保存图片到本地(照相功能) -samhy
  3. “23岁本科生发14篇SCI”,文章被学校官网悄悄删了,你怎么看?
  4. java字符串转日期_JAVA字符串转日期或日期转字符串
  5. ubuntu php 支持mysql_在ubuntu16.04上安装php7 mysql5.7 nginx1.10并支持http2
  6. cocos2d, Box2D
  7. 申请成为qq互联个人开发者步骤(注意事项)2018
  8. CCF 201612-2 工资计算 java 解题
  9. 基于框架的全局配置模型
  10. python异常处理知识点_一文掌握 Python 异常处理的所有知识点
  11. 【深入篇】Android常用布局方式简介
  12. 【LKA】国内车道相关数据
  13. linux和主机共享文件,设置Linux虚拟机与主机共享文件的方法
  14. Android SDK是什么
  15. 『C++』endl、ends和flush的区别
  16. python_while 循环_珠穆朗玛峰
  17. 从0开始,手把手搭建个人网站
  18. 表达式的LenB(123程序设计ABC)的值是27吗
  19. 织梦DEDE正则查找批量替换数据库自定义内容
  20. 解决phpStudy端口占用的问题

热门文章

  1. ZZULIOJ-1012,求绝对值(Java)
  2. 如何在未越狱iOS设备上安装IPA
  3. 大炮打蚊子(已AC)
  4. 对称加密 非对称加密
  5. JAYのpython学习笔记——数据结构之列表
  6. centos 7, 8 的区别
  7. js常用效果代码封装
  8. 前后端是如何交互的?
  9. 机器学习面试题 (一)
  10. 再读德鲁克#2 如何提升生产率