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中异常(Exception)的总结的更多相关文章

  1. Python中异常和JSON读写数据

    异常可以防止出现一些不友好的信息返回给用户,有助于提升程序的可用性,在java中通过try ... catch ... finally来处理异常,在Python中通过try ... except .. ...

  2. Python 中异常嵌套

    在Python中,异常也可以嵌套,当内层代码出现异常时,指定异常类型与实际类型不符时,则向外传,如果与外面的指定类型符合,则异常被处理,直至最外层,运用默认处理方法进行处理,即停止程序,并抛出异常信息 ...

  3. Oracle存储过程中异常Exception的捕捉和处理

    Oracle存储过程中异常的捕捉和处理 CREATE OR REPLACE Procedure Proc_error_process ( v_IN in Varchar2, v_OUT Out Var ...

  4. 『无为则无心』Python函数 — 39、Python中异常的传播

    目录 1.异常的传播 2.如何处理异常 1.异常的传播 当在函数中出现异常时,如果在函数中对异常进行了处理,则异常不会再继续传播.如果函数中没有对异常进行处理,则异常会继续向函数调用者传播.如果函数调 ...

  5. 四十二、python中异常

    1.常用异常: AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性xIOError 输入/输出异常:基本上是无法打开文件ImportError 无法引入模块或 ...

  6. Python中异常打印——面向程序猿

    import logging # logging.disable(logging.CRITICAL) logging.basicConfig(filename="loggingBug.txt ...

  7. Python基础之:Python中的异常和错误

    目录 简介 Python中的内置异常类 语法错误 异常 异常处理 抛出异常 异常链 自定义异常 finally 简介 和其他的语言一样,Python中也有异常和错误.在 Python 中,所有异常都是 ...

  8. 《java中异常和错误》

    异常和错误的区别. 异常: 在Java中程序的错误主要是语法错误和语义错误,一个程序在编译和运行时出现的错误我们统一称之为异常,它是VM(虚拟机)通知你的一种方式,通过这种方式,VM让你知道,你(开发 ...

  9. Python中获取异常(Exception)信息

    异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置.下面介绍几种python中获取异常信息的方法,这里获取异常(Exception)信息采用try...except...程序 ...

随机推荐

  1. Android_Dialog

    layout.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xml ...

  2. Mac Mysql5.7.11安装和卸载

    初学者,被mysql的安装弄晕了,所以在此记录一下. 安装 去http://www.mysql.com/downloads/, 选择最下方的MySQL Community Edition,点击MySQ ...

  3. Linux系统上安装软件(ftp服务器)

    一:安装ftp服务器 在安装linux系统的时候,自定义软件包安装时,我已经勾选了ftp服务器,所以已经 安装过了,如果没有勾选,需要额外下载ftp的安装包,进行安装. ftp服务器搭建过程中遇到的问 ...

  4. tab选项卡

    1 <!doctype html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or ...

  5. .NET学习笔记(2) — IIS服务器环境搭建

    目录 一:开启Windows系统自带的IIS服务器方法 二:备注 三:常见问题     一:开启Windows系统自带的IIS服务器方法   第一步:安装IIS,控制面板->程序和功能-> ...

  6. List的add方法与addAll方法的区别

    add是将传入的参数作为当前List中的一个Item存储,即使你传入一个List也只会另当前的List增加1个元素addAll是传入一个List,将此List中的所有元素加入到当前List中,也就是当 ...

  7. 【C#4.0图解教程】笔记(第1章~第8章)

    第1章 C#和.NET框架 1..NET框架的组成 .NET框架由三部分组成(严格来说只有CLR和FCL(框架类库)两部分),如图 执行环境称为:CLR(公共语言运行库),它在运行期管理程序的执行. ...

  8. 第二篇、HTML5新增标签

    <html> <head> <meta charset="UTF-8"> <title>html5新增的标签</title&g ...

  9. 学习笔记---C++虚函数,纯虚函数

    1 .虚函数 假设people是man的父类,people类和man类都定义了实函数walk() people* p = new man(); p->walk(); 这里P执行的是people类 ...

  10. Windows server2008/2012 安装oracle 11 创建实例HANG住在百分之2

    Windows server2008/2012 安装oracle 11.2.0.1的时候,可能会在创建数据库实例的时候卡在百分之2的地方. 这个时候可以 1.点击开始菜单,在“搜索程序和文件”中输入“ ...