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>>