zl程序教程

您现在的位置是:首页 >  Python

当前栏目

python中try finally的用法_Python中的try-finally子句

2023-04-18 13:13:54 时间

您可以将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语句中对其进行处理。