Home  >  Article  >  Backend Development  >  Python中的异常处理简明介绍

Python中的异常处理简明介绍

WBOY
WBOYOriginal
2016-06-10 15:15:251003browse

python异常处理机制和java类似,采用try-except-finally的结构.

try-except检测异常

格式

复制代码 代码如下:

try:
    try_statement
except (ErrorType1, ErrorType2),e:
    handle_statement
finally:
    finally_statement

实例
复制代码 代码如下:

#!/usr/bin/python
try:
    a=12
    b=0
    c = a/b
except Exception, e:
    print  "Exception occurs: " , e
finally:
    print "finally handle!"

上下文管理器(with…as…语句)

with语句可以特别适用于首先打开资源最后释放资源的场景,因为它会自动释放占有的资源,不需要显示地释放资源

格式

复制代码 代码如下:

with context_expr [as var]:
    with_statement

raise引发异常

格式

复制代码 代码如下:

raise Exception[, args] or raise Exception(args)

实例
复制代码 代码如下:

raise Exception(‘exampleException')

断言

检测程序的关键点,断言不成功的时候触发AssertError(断言错误)
格式如下

复制代码 代码如下:

assert expression[, arguements]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn