如何列印 Python 異常/錯誤層次結構?


在學習如何列印 Python 異常之前,我們將瞭解什麼是異常。

當程式無法按照預期執行時,就會發生異常。當發生意外錯誤或事件時,Python 會丟擲異常。

異常通常既有效也無效。可以透過多種方式在程式中透過異常來管理錯誤和異常情況。當您懷疑程式碼可能會產生錯誤時,可以使用異常處理技術。這可以防止軟體崩潰。

常見異常

  • IOError(輸入輸出錯誤)− 當檔案無法開啟時

  • ImportError− 當 Python 找不到模組時

  • ValueError− 當用戶按下中斷鍵(通常是 ctrl+c 或 delete)時發生

  • EOFError(檔案結束錯誤)− 當 input() 或 raw_input() 在沒有讀取任何資料的情況下遇到檔案結束 (EOF) 條件時導致。

Python 異常/錯誤層次結構

Python 異常層次結構由各種內建異常組成。此層次結構用於處理各種型別的異常,因為繼承的概念也出現在其中。

在 Python 中,所有內建異常必須是派生自 BaseException 的類的例項。

可以透過匯入 Python 的 inspect 模組來列印此異常或錯誤層次結構。使用 inspect 模組,可以執行型別檢查,檢索方法的原始碼,檢查類和函式,以及檢查直譯器堆疊。

在本例中,可以使用 inspect 模組中的 getclasstree() 函式來構建樹形層次結構。

語法

inspect.getclasstree(classes, unique = False)

示例

可以使用 inspect.getclasstree() 來排列巢狀類列表的層次結構。在巢狀列表出現的地方,派生自緊隨其後的類的類也將出現。

# Inbuilt exceptions: # Import the inspect module import inspect as ipt def tree_class(cls, ind = 0): print ('-' * ind, cls.__name__) for K in cls.__subclasses__(): tree_class(K, ind + 3) print ("Inbuilt exceptions is: ") # THE inspect.getmro() will return the tuple. # of class which is cls's base classes. #The next step is to create a tree hierarchy. ipt.getclasstree(ipt.getmro(BaseException)) # function call tree_class(BaseException)

輸出

在此示例中,我們僅列印了 BaseException 的層次結構;要列印其他異常的層次結構,請將“Exception”作為引數傳遞給函式。

Inbuilt exceptions is:
BaseException
--- Exception
------ TypeError
------ StopAsyncIteration
------ StopIteration
------ ImportError
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
------ TokenError
------ StopTokenizing
------ ClassFoundException
------ EndOfBlock
--- GeneratorExit
--- SystemExit
--- KeyboardInterrupt

示例

另一個用於顯示 Python 異常/錯誤層次結構的示例如下所示。在這裡,我們試圖使用“Exception”顯示其他異常的層次結構 -

import inspect print("The class hierarchy for built-in exceptions is:") inspect.getclasstree(inspect.getmro(Exception)) def classtree(cls, indent=0): print('.' * indent, cls.__name__) for subcls in cls.__subclasses__(): classtree(subcls, indent + 3) classtree(Exception))

輸出

輸出如下所示 -

The class hierarchy for built-in exceptions is:
Exception
... TypeError
... StopAsyncIteration
... StopIteration
... ImportError
...... ModuleNotFoundError
...... ZipImportError
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
... Verbose
... TokenError
... StopTokenizing
... EndOfBlock

結論

透過本文,我們學習瞭如何使用 Python 的 inspect 模組列印層次結構中的異常錯誤。

更新於: 2023年2月24日

3K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.