Python中獲取異常(Exception)信息

  異常信息的獲取對於程序的調試很是重要,能夠有助於快速定位有錯誤程序語句的位置。下面介紹幾種python中獲取異常信息的方法,這裏獲取異常(Exception)信息採用try...except...程序結構。以下所示python

try:

  ...

except Exception, e:

  ...

 

一、str(e)函數

返回字符串類型,只給出異常信息,不包括異常信息的類型,如1/0的異常信息spa

'integer division or modulo by zero'命令行

二、repr(e)調試

給出較全的異常信息,包括異常信息的類型,如1/0的異常信息code

"ZeroDivisionError('integer division or modulo by zero',)"orm

三、e.message對象

得到的信息同str(e)blog

四、採用traceback模塊字符串

  須要導入traceback模塊,此時獲取的信息最全,與python命令行運行程序出現錯誤信息一致。使用traceback.print_exc()打印異常信息到標準錯誤,就像沒有獲取同樣,或者使用traceback.format_exc()將一樣的輸出獲取爲字符串。你能夠向這些函數傳遞各類各樣的參數來限制輸出,或者從新打印到像文件類型的對象。

 

示例以下:

import traceback

print '########################################################'
print "1/0 Exception Info"
print '---------------------------------------------------------'
try:
    1/0
except Exception, e:
    print 'str(Exception):\t', str(Exception)
    print 'str(e):\t\t', str(e)
    print 'repr(e):\t', repr(e)
    print 'e.message:\t', e.message
    print 'traceback.print_exc():'; traceback.print_exc()
    print 'traceback.format_exc():\n%s' % traceback.format_exc()
print '########################################################'
print '\n########################################################'  
print "i = int('a') Exception Info"
print '---------------------------------------------------------'
try:
    i = int('a')
except Exception, e:
    print 'str(Exception):\t', str(Exception)
    print 'str(e):\t\t', str(e)
    print 'repr(e):\t', repr(e)
    print 'e.message:\t', e.message
    print 'traceback.print_exc():'; traceback.print_exc()
    print 'traceback.format_exc():\n%s' % traceback.format_exc()
print '########################################################' 

 

示例結果

 

參考資料:

Getting the exception value in Python

相關文章
相關標籤/搜索