Python - try-finally 塊



Python try-finally 塊

在 Python 中,try-finally 塊用於確保某些程式碼一定會執行,無論是否引發異常。與處理異常的 try-except 塊不同,try-finally 塊專注於必須執行的清理操作,確保資源得到正確釋放並完成關鍵任務。

語法

try-finally 語句的語法如下:

try:
   # Code that might raise exceptions
   risky_code()
finally:
   # Code that always runs, regardless of exceptions
   cleanup_code()
在 Python 中,使用 try 塊進行異常處理時,可以選擇包含 except 子句來捕獲特定異常,或者包含 finally 子句來確保執行某些清理操作,但不能同時包含兩者。

示例

讓我們考慮一個示例,我們希望以寫入模式 ("w") 開啟一個檔案,向其中寫入一些內容,並使用 finally 塊確保無論成功或失敗都關閉檔案:

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")
   fh.close()

如果您沒有許可權以寫入模式開啟檔案,則會產生以下輸出

Error: can't find file or read data

相同的示例可以更簡潔地編寫如下:

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 語句,則會在那裡進行處理。

帶引數的異常

異常可以帶有一個引數,該引數是一個值,提供有關問題的更多資訊。引數的內容因異常而異。您可以透過在 except 子句中提供一個變數來捕獲異常的引數,如下所示:

try:
   You do your operations here
   ......................
except ExceptionType as Argument:
   You can print value of Argument here...

如果您編寫程式碼來處理單個異常,則可以在 except 語句中在異常名稱之後新增一個變數。如果您正在捕獲多個異常,則可以在異常元組之後新增一個變數。

此變數接收異常的值,主要包含異常的原因。變數可以接收單個值或多個值(以元組的形式)。此元組通常包含錯誤字串、錯誤號和錯誤位置。

示例

以下是一個針對單個異常的示例:

# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError as Argument:
      print("The argument does not contain numbers\n",Argument)
# Call above function here.
temp_convert("xyz")

它將產生以下輸出

The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
廣告