Heim  >  Artikel  >  Backend-Entwicklung  >  Python中的异常处理简明介绍

Python中的异常处理简明介绍

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

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]
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn