在 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 子句始終執行,無論是否發生異常。

更新於: 2020-06-30

842 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告