在 Python 中列印異常
Vaibhav Vaibhav
2023年1月30日
Python
Python Exception
在 Python 中,異常是錯誤。Python 中存在許多錯誤或異常,例如 TypeError、SyntaxError、KeyError 和 AttributeError 等。我們在 Python 中使用 try-except-finally 來處理這些異常,因為沒有這些塊,這些異常將終止程式的執行。Python 中的 try-except-finally 塊可用於列印這些異常,而無需停止程式的執行。
在 Python 中使用 try-except-finally 塊列印異常
考慮以下程式碼片段。
dictionary = {
"hello": "world",
}
number = 25
try:
number = number + dictionary["hello"]
print(number)
except Exception as e:
print(repr(e))
輸出:
TypeError("unsupported operand type(s) for +: 'int' and 'str'",)
在上面的程式碼中,我們首先用字典 hello 作為指向字串值 world 的鍵和變數 number 的字典進行初始化。然後在 try 塊中,我們嘗試訪問儲存在字典中的字串值,並將其新增到 number 變數中。
該宣告在實際上和概念上都是錯誤的,因為不可能在整數中新增字串。因此,except 塊會捕獲此錯誤,並在控制檯中輸出與此異常關聯的 Exception 物件。
在 Python 中使用 traceback 模組進行列印異常
Python 有一個內建模組 traceback,用於列印和格式化異常。而且,它很容易在控制檯中列印整個異常。
在 Python 中,你可以使用 raise 關鍵字手動引發異常。在以下程式碼段中,我們將使用 raise 關鍵字在 try 塊內引發異常。
import traceback
try:
raise KeyError
except Exception as e:
traceback.print_exc()
輸出:
Traceback (most recent call last):
File ".\main.py", line 4, in <module>
raise KeyError
KeyError
在上面的程式碼中,我們引發了一個 KeyError 異常,並使用了 traceback 模組中的 print_exc() 函式來列印該異常。該函式列印有關異常的資訊,是 traceback.print_exception(*sys.ex_info(), limit, file, chain) 的簡寫。
要了解有關 print_exception() 函式的更多資訊,請參考官方文件
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Vaibhav Vaibhav
