1. 程式人生 > 其它 >python traceback模組使用 異常的獲取與處理

python traceback模組使用 異常的獲取與處理

1、traceback.print_exc()
2、traceback.format_exc()
3、traceback.print_exception()

簡單說下這三個方法是做什麼用的:

1、print_exc():是對異常棧輸出
2、format_exc():是把異常棧以字串的形式返回,print(traceback.format_exc()) 就相當於traceback.print_exc()
3、print_exception():traceback.print_exc()實現方式就是traceback.print_exception(sys.exc_info()),可以點sys.exc_info()進去看看實現
問題:traceback.print_exc()和traceback.format_exc()有什麼區別呢? format_exc()返回字串,print_exc()則直接給打印出來。 即traceback.print_exc()與print traceback.format_exc()效果是一樣的。 print_exc()還可以接受file引數直接寫入到一個檔案。比如 traceback.print_exc(file=open('tb.txt','w+')) 寫入到tb.txt檔案去。

traceback.print_exc([limit[, file]])

print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)的簡寫

import traceback


def abc():
    try:
        1/0
    except Exception as e:
        traceback.print_exc()


if __name__ == '__main__':
    abc()
    1/0
ZeroDivisionError: division by zero

traceback.format_exc([limit])

類似於print_exc(limit), 但是返回字串而不是輸出到file.

import traceback


try:
    raise ValueError("
msg") except Exception as e: print(traceback.format_exc())
raise ValueError("msg")
ValueError: msg

traceback.print_exc()函式只是traceback.print_exception()函式的一個簡寫形式,而它們獲取異常相關的資料都是通過sys.exc_info()函式得到的。

import sys
import traceback


def func(a, b):
    return a / b

if __name__ == '__main__':
    try:
        func(1, 0)
    except Exception as e:
        print('print_exception()')
        exc_type, exc_value, exc_tb = sys.exc_info()
        print('the exc type is:', exc_type)
        print('the exc value is:', exc_value)
        print('the exc tb is:', exc_tb)
        traceback.print_exception(exc_type, exc_value, exc_tb)

返回結果

print_exception()
Traceback (most recent call last):
the exc type is: <class 'ZeroDivisionError'>
  File , line 16, in <module>
the exc value is: division by zero
    func(1, 0)
the exc tb is: <traceback object at 0x000002583038D188>
  File , line 12, in func
    return a / b
ZeroDivisionError: division by zero

sys.exc_info()返回的值是一個元組,其中第一個元素,exc_type是異常的物件型別,exc_value是異常的值,exc_tb是一個traceback物件,物件中包含出錯的行數、位置等資料。

然後通過print_exception函式對這些異常資料進行整理輸出。

三種方式列印結果是一樣的。在開發時,做除錯是很方便的。也可以把這種異常棧寫入日誌。

logging.exception(ex)

# 指名輸出棧蹤跡, logging.exception的內部也是包了一層此做法
logging.error(ex, exc_info=1) 

# 更加嚴重的錯誤級別 
logging.critical(ex, exc_info=1)