Python 中的 try-finally 子句
pythonserver side programmingprogramming更新于 2025/4/21 1:48:17
您可以将 finally: 块与 try: 块一起使用。finally 块是放置必须执行的任何代码的地方,无论 try 块是否引发异常。try-finally 语句的语法是这样的 −
try: 您在此处执行操作; ...................... 由于任何异常,可能会跳过此操作。 finally: 这将始终执行。 ......................
您不能将 else 子句与 finally 子句一起使用。
示例
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception processing!!")
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 processing!!")
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 语句中处理该异常。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

