finally子句
#Python中的finally子句需要和try子句一起使用,组成try/finally的语句形式,try/finally语句无论发生异常与否都将执行最后的代码。
#示例如下:
1 #!/usr/bin/python3 2 #-*-coding:UTF-8-*- 3 #异常9.10_finally 4 5 def use_finally(x,y): 6 try: 7 a=x/y 8 finally: 9 print('No matter what happened,I will show in front of you') 10 use_finally(2,0)
#执行结果如下:
1 D:\Pythonworkspace>python 异常9.10_finally.py 2 No matter what happened,I will show in front of you 3 Traceback (most recent call last): 4 File "异常9.10_finally.py", line 10, in <module> 5 use_finally(2,0) 6 File "异常9.10_finally.py", line 7, in use_finally 7 a=x/y 8 ZeroDivisionError: division by zero
#由执行结果看到,finally子句被执行了,无论try子句是否发生异常,finally都会被执行。
#这里有个疑问,虽然执行了finally子句,但最后还是抛出了异常,是否可以使用except截获异常呢?
#可以使用except截获异常。try、except、else和finally可以组合使用,但是要记得else在except之后,finally在else之后。示例如下:
1 #!/usr/bin/python3 2 #-*-coding:UTF-8-*- 3 #异常9.10_finally 4 5 def use_finally(x,y): 6 try: 7 a=x/y 8 except ZeroDivisionError: 9 print('Some bad thing happened:division by zero') 10 finally: 11 print('No matter what happened,I whill show in front of you') 12 13 use_finally(2,0)
#执行结果如下:
1 D:\Pythonworkspace>python 异常9.10_finally.py 2 Some bad thing happened:division by zero 3 No matter what happened,I whill show in front of you
#由执行结果看到,先执行了except子句的输出语句,后面跟着执行了finally子句的输出语句。如果在添加else子句,当程序正常运行时会执行else子句,然后执行finally子句。在有finally的异常处理程序中,finally中的子句一定是最后执行的。finally子句在关闭文件或数据库连接时非常有用
#在Python2.5之前的版本中,finally需要独立使用,不能与try语句配合。在Python2.5之后才支持这些语句的组合使用。