python异常处理机制和java类似,采用try-except-finally的结构.
[b]try-except检测异常[/b]
格式
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!"
[b]上下文管理器(with…as…语句)[/b]
with语句可以特别适用于首先打开资源最后释放资源的场景,因为它会自动释放占有的资源,不需要显示地释放资源
格式
with context_expr [as var]:
with_statement
[b]raise引发异常[/b]
格式
raise Exception[, args] or raise Exception(args)
实例
raise Exception(‘exampleException')
[b]断言[/b]
检测程序的关键点,断言不成功的时候触发AssertError(断言错误)
格式如下
assert expression[, arguements]