1. 程式人生 > >【python】 使用sys.exc_info自己捕獲異常詳細資訊

【python】 使用sys.exc_info自己捕獲異常詳細資訊

Python 使用sys.exc_info自己捕獲異常詳細資訊

一般程式中,我們需要對異常進行捕獲來保證程式的健壯。但是debug的時候,我們可能需要異常的詳細資訊,這時可以使用sys.exec_info來處理:

import traceback
import sys
try:
     raise ValueError('this is a exp')
except Exception as ex:
    ex_type, ex_val, ex_stack = sys.exc_info()
    print(ex_type)
    print(ex_val)
    for stack in
traceback.extract_tb(ex_stack): print(stack)

將以上程式碼儲存為檔案test.py, 執行可以看到以下結果:

% python3 test.py 
<class 'ValueError'>
this is a exp
<FrameSummary file test.py, line 4 in <module>>