python 捕捉错误,exception,traceback和sys.exc_info()比较

import traceback,sys
import requests

try :
    requests.get('dsdsd')  ##故意让他出错
except Exception,e:
    print '33[1;35;40m%s33[0m'%str(e)
    #traceback.print_exc()
    print '33[4;32;0m%s33[0m'%traceback.format_exc()
    info = sys.exc_info()
    print    '33[7;32;0m%s : %s 33[0m'%(info[0],info[1])
    #sys.exit(666)

print 'hello'

exception 能看到错误提示

traceback能看到具体的错误在哪一行,当try里面包含了上百行代码,包括功能现金的代码,如果只是用exception打印,可能不知道是哪出错了,而且不好调试定位,taraceback就十分好了。

sys.exc_info能看到错误类型和错误提示。

原文地址:https://www.cnblogs.com/ydf0509/p/7341116.html