如何列印 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 模組列印層次結構中的異常錯誤。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP