如何捕獲並列印 Python 異常訊息?


Python 異常訊息可以透過不同的方式捕獲並列印,如以下兩個程式碼示例中所示。在第一個示例中,我們使用了異常物件的 message 屬性。

示例

try:
a = 7/0
print float(a)
except BaseException as e:
print e.message

輸出

integer division or modulo by zero

對於給定的程式碼,我們匯入 sys 模組並使用 sys.exc_value 屬性捕獲並列印異常訊息。

示例

import sys
def catchEverything():
try:
a = 'sequel'
b = 0.8
print a + b
except Exception as e:
print sys.exc_value
catchEverything()

輸出

cannot concatenate 'str' and 'float' objects

更新於:2020 年 2 月 12 日

2000+ 次瀏覽

開啟你的事業

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.