在 Python 中將異常提升到另一個異常


在 Python 中將特殊情況提升到另一個異常包括捕獲和處理原始特殊情況的方法,然後引發一個新的異常,其中包含對初始異常的額外上下文。此過程允許開發人員自定義或包裝異常,從而實現更好的錯誤處理和更有意義的錯誤訊息。透過組合不同的異常、建立複合異常或使用“from”關鍵字,開發人員可以透過精確地傳達異常情況的性質來提高其程式碼的魯棒性和可靠性。瞭解這些方法使開發人員能夠有效地處理和管理 Python 程式中的錯誤。

方法 1:在異常塊內引發異常

第一種方法包括在現有的異常塊內引發異常。此方法允許您捕獲初始異常並將其包裝在一個新的異常中。以下是所涉及步驟的演算法表示 -

演算法

  • 步驟 1 - 將引發異常的程式碼封裝在 try-except 塊中。

  • 步驟 2 - 在 except 塊中,使用合適的異常類捕獲第一個異常。

  • 步驟 3 - 將第一個異常作為引數傳遞給名為 new_exception 的變數。

  • 步驟 4 - 使用“raise”關鍵字引發新的異常。

示例

class CustomException(Exception):
   def __str__(self):
      return "This is a custom exception."

try:
   # Code that may raise an exception
   raise ValueError("An error occurred.")
except ValueError as original_exception:
   new_exception = CustomException(str(original_exception))
   raise new_exception

輸出

Traceback (most recent call last):
  File "/home/cg/root/11237/main.py", line 8, in <module>
   raise ValueError("An error occurred.")
ValueError: An error occurred.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/cg/root/11237/main.py", line 11, in <module>
   raise new_exception
__main__.CustomException: This is a custom exception

方法 2:透過建立複合異常引發異常

第二種方法包括透過將多個異常組合到單個異常中來建立複合異常。當您需要引發一個表示多個異常情況的單個異常時,此方法很有用。以下是步驟 -

演算法

  • 步驟 1 - 定義表示不同異常情況的多個異常類。

  • 步驟 2 - 建立一個名為 CompundException() 的類,該類從基異常類或任何其他合適的異常類繼承。

  • 步驟 3 - 引發新異常類的異常,如果檔案未找到則傳遞合適的異常,並在 except 塊中,將異常提升到另一個異常,即複合異常。

示例

class FileNotFoundError(Exception):
   pass

class PermissionDeniedError(Exception):
   pass

class CompoundException(Exception):
   def __init__(self, file_error, permission_error):
      self.file_error = file_error
      self.permission_error = permission_error

try:
   raise FileNotFoundError("File not found.")
except FileNotFoundError as file_error:
   try:
      raise PermissionDeniedError("Permission denied.")
   except PermissionDeniedError as permission_error:
      raise CompoundException(file_error, permission_error)

輸出

Traceback (most recent call last):
  File "/home/cg/root/84000/main.py", line 13, in <module>
   raise FileNotFoundError("File not found.")
__main__.FileNotFoundError: File not found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/cg/root/84000/main.py", line 16, in <module>
   raise PermissionDeniedError("Permission denied.")
__main__.PermissionDeniedError: Permission denied.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/cg/root/84000/main.py", line 18, in <module>
   raise CompoundException(file_error, permission_error)
__main__.CompoundException: (FileNotFoundError('File not found.'), PermissionDeniedError('Permission denied.'))

方法 3:使用“from”關鍵字引發異常

第三種方法使用“from”關鍵字來引發一個新的異常,該異常保留原始異常的回溯。這允許您提供其他上下文,而不會丟失原始異常的詳細資訊。以下是步驟 -

演算法

  • 步驟 1 - 將引發異常的程式碼封裝在 try-except 塊中。

  • 步驟 2 - 在 try-except 塊中,使用合適的異常捕獲第一個異常。

  • 步驟 3 - 使用“raise”關鍵字引發新的異常,後跟“from”關鍵字和第一個異常。

示例

#Use try block
try:
   # Code that may raise an exception
   raise ValueError("An error occurred.")
#Utilize except block
except ValueError as original_exception:
   raise TypeError("Invalid type") from original_exception

輸出

Traceback (most recent call last):
  File "/home/cg/root/26818/main.py", line 4, in <module>
   raise ValueError("An error occurred.")
ValueError: An error occurred.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/cg/root/26818/main.py", line 7, in <module>
   raise TypeError("Invalid type") from original_exception
TypeError: Invalid type

結論

在 Python 中將異常提升到另一個異常可以透過多種方法實現,具體取決於您的特定需求。這些方法提供了靈活性,並允許您更有效地處理 Python 程式中的異常情況。透過理解和應用這些方法,您將提高程式碼的可靠性和健壯性。

更新於: 2023-08-29

204 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.