Exception 資訊 - jenhaoyang/backend_blog GitHub Wiki
import sys, traceback
def lumberjack():
bright_side_of_death()
def bright_side_of_death():
return tuple()[0]
try:
lumberjack()
except IndexError:
formatted_lines = traceback.format_exc().splitlines()
error_string= "\n".join(formatted_lines[-3:])
print(error_string)
# -*- coding: utf-8 -*-
import sys
import traceback
import test
try:
test.run()
except Exception as e:
# print(e)
error_class = e.__class__.__name__ #取得錯誤類型
detail = e.args[0] #取得詳細內容
cl, exc, tb = sys.exc_info() #取得Call Stack
lastCallStack = traceback.extract_tb(tb)[-1] #取得Call Stack的最後一筆資料
fileName = lastCallStack[0] #取得發生的檔案名稱
lineNum = lastCallStack[1] #取得發生的行號
funcName = lastCallStack[2] #取得發生的函數名稱
errMsg = "File \"{}\", line {}, in {}: [{}] {}".format(fileName, lineNum, funcName, error_class, detail)
print(errMsg)
參考:
https://docs.python.org/3/library/traceback.html#traceback-examples
https://dotblogs.com.tw/caubekimo/2018/09/17/145733
https://www.jianshu.com/p/a8cb5375171a