在 Python 中定义清理操作
pythonserver side programmingprogramming更新于 2025/5/12 23:40:17
当我们希望程序执行此特定任务时,会发生许多情况,无论它是完美运行还是抛出一些错误。我们主要使用 try 和 except 块来捕获任何错误或异常。
“try” 语句提供了非常有用的可选子句,用于定义在任何情况下都必须执行的‘清理操作’。例如 −
>>> try:
raise SyntaxError
finally:
print("Learning Python!")
Learning Python!
Traceback (most recent call last):
File "<pyshell#11>", line 2, in <module>
raise SyntaxError
File "<string>", line None
SyntaxError: <no detail available>
final 子句无论如何都会执行,但是 else 子句只有在未引发异常时才会执行。
示例 1 − 考虑以下示例,其中一切正常并且写入文件时没有异常(程序正常运行),将输出以下 −
file = open('finally.txt', 'w')
try:
file.write("Testing1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
运行上述程序,将得到 −
Writing to file. Write successful. File closed.
示例 2 −让我们尝试通过将文件设为只读并尝试写入文件来引发异常,从而导致它引发异常。
file = open('finally.txt', 'r')
try:
file.write("Testing1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
上述程序将给出输出,类似于 −
Could not write to file. File closed.
如果我们遇到错误,但我们没有放置任何 except 子句来处理它。在这种情况下,将首先执行清理操作(finally 块),然后编译器会引发错误。让我们通过以下示例 − 来理解这个概念
示例
file = open('finally.txt', 'r')
try:
file.write(4)
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
输出
File closed. Traceback (most recent call last): File "C:/Python/Python361/finally_try_except1.py", line 4, in <module> file.write(4) TypeError: write() argument must be str, not int
因此,从上面我们可以看出,无论是否发生异常,finally 子句总是会执行。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

