traceback 捕獲原始異常。

2021-06-18 13:52:47 字數 1251 閱讀 6714

def trace_err(extend_msg=none):

msg = '' if extend_msg is none else extend_msg

msg += '\n------------------- local arguments -------------------\n'

for k, v in sys._getframe(1).f_locals.iteritems():

msg += (' >>> ' + str(k) + ': ' + str(v) + '\n')

msg += '--------------------- error information----------------------\n'

exc_info = traceback.format_exception(*sys.exc_info()) #

msg += ''.join(exc_info)

msg += '---------------------- end -----------------------\n'

print msg

def test(c):

b =

try:

raise

except:

trace_err('other information')

test(30)

該程式通過traceback自動捕獲異常的原始資訊,定位到行,相對於列印except的異常資訊,內容更豐富。

引數extend_msg為額外的列印資訊。

該程式先列印額外資訊,再列印本地變數,最後列印出錯的原始資訊:

other information

------------------- local args -------------------

>>> c: 30

>>> b:

--------------------- error ----------------------

traceback (most recent call last):

file "log.py", line 145, in test

raise

typeerror: exceptions must be old-style classes or derived from baseexception, not nonetype

---------------------- end -----------------------

traceback 異常跟蹤

traceback 用來跟蹤異常返回資訊。異常物件預設包含stacktrace相關的資訊,通過異常物件的相關方法printstacktrace 和getstacktrace 等方法就可以取到異常棧資訊,能列印log輔助除錯。1 author zechary 2 3import traceback 4...

traceback模組 獲取異常資訊

除了使用 sys.exc info 方法獲取更多的異常資訊之外,還可以使用 traceback 模組,該模組可以用來檢視異常的傳播軌跡,追蹤異常觸發的源頭。下面示例顯示了如何顯示異常傳播軌跡 class selfexception exception pass def main firstmetho...

mysql異常捕獲 MySql中捕獲異常的方法

下面是程式設計之家 jb51.cc 通過網路收集整理的 片段。mysql中是否能有sqlserver的 error變數呢,或者如c 中的try catch語法呢。答案是肯定的,例項 如下 code drop procedure if exists sp call jobs create proced...