Python中的try-finally子句
您可以将finally:块与try:块一起使用。finally块是放置必须执行的所有代码的位置,无论try块是否引发异常。try-finally语句的语法是:
try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
您不能同时使用else子句和finally子句。
示例
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"输出结果
如果您无权以写入模式打开文件,则将产生以下结果-
Error: can't find file or read data
相同的例子可以更清晰地写成如下-
示例
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"当try块中引发异常时,执行立即转到finally块。执行完finally块中的所有语句后,如果在try-except语句的下一个较高层中存在,则再次引发异常,并在except语句中对其进行处理。
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便