在 Python 中定义清理操作
在许多情况下,我们希望我们的程序执行特定的任务,无论它是否完美运行或抛出一些错误。大多数情况下,为了捕获任何错误或异常,我们使用 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>无论发生什么,最终的子句都将执行,但是,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 子句始终执行,无论是否发生异常。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP