try: block except [exception,[data…]]: block try: block except [exception,[data...]]: block else: block該種異常處理語法的規則是:
try: f = open(「file.txt」,」r」) except IOError, e: print e捕獲到的IOError錯誤的詳細緣由會被放置在對象e中,而後運行該異常的except代碼塊,也可使用如下方法來捕獲全部的異常:
try: a=b b=c except Exception,ex: print Exception,":",ex使用except子句須要注意的事情,就是多個except子句截獲異常時,若是各個異常類之間具備繼承關係,則子類應該寫在前面,不然父類將會直接截獲子類異常,放在後面的子類異常也就不會執行到了。
try: block finally: block該語句的執行規則是:
try: raise MyError #本身拋出一個異常 except MyError: print 'a error' raise ValueError,'invalid argument'捕捉到的內容爲:
type = VauleError message = invalid argument3、跟蹤查看異常
try: block except: traceback.print_exc()
4、採用sys模塊回溯最後的異常 python
import sys try: block except: info=sys.exc_info() print info[0],":",info[1]
或者以以下的形式: app
import sys tp,val,td = sys.exc_info()sys.exc_info()的返回值是一個tuple, (type, value/message, traceback)
#coding:utf-8 #基於python2.6 import logging,os,time,traceback class LOG: def __init__(self,logger): self.fileHandlerName = '' self.fileHandler = None self.loggerName = logger self.logger = logging.getLogger(logger) self.logger.setLevel(logging.DEBUG) self.formatter = logging.Formatter("=========================\ntime:%(asctime)s \nlogger:%(name)s \nlevel:%(levelname)s \nfile:%(filename)s \nfun:%(funcName)s \nlineno:%(lineno)d \nmessage:%(message)s") # 控制檯 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(self.formatter) self.logger.addHandler(ch) path = os.path.abspath(os.path.dirname(__file__)) + '/log/'+self.loggerName+'/' print 'log path=',path def setfh(self): fname = time.strftime("%Y%m%d%H") if fname!=self.fileHandlerName: #移除原來的句柄 if self.fileHandler!=None : self.logger.removeHandler(self.fileHandler) #設置日誌文件保存位置 path = os.path.abspath(os.path.dirname(__file__)) + '/log/'+self.loggerName+'/' print path if os.path.isdir(path) == False: os.makedirs(path) fh = logging.FileHandler(path+fname+'.log') fh.setLevel(logging.DEBUG) fh.setFormatter(self.formatter) self.logger.addHandler(fh) self.fileHandlerName = fname self.fileHandler = fh #格式化日誌內容 def _fmtInfo(self,msg): if len(msg)==0: msg = traceback.format_exc() return msg else: _tmp = [msg[0]] _tmp.append(traceback.format_exc()) return '\n**********\n'.join(_tmp) #封裝方法 def debug(self,*msg): _info = self._fmtInfo(msg) try: self.setfh() self.logger.debug(_info) except: print 'mylog debug:' + _info def error(self,*msg): _info = self._fmtInfo(msg) try: self.setfh() self.logger.error(_info) except: print 'mylog error:' + _info def info(self,*msg): _info = self._fmtInfo(msg) try: self.setfh() self.logger.error(_info) except: print 'mylog info:' + _info def warning(self,*msg): _info = self._fmtInfo(msg) try: self.setfh() self.logger.error(_info) except: print 'mylog warning:' + _info if __name__=='__main__': log = LOG('fight') try: print 1/0 except: log.error() #使用系統本身的錯誤描述 try: print 2/0 except: log.error('搞錯了,分母不能爲0') #使用本身的錯誤描述
運行一下,咱們會在該文件目錄下的log/fight下看到一個日誌文件,記錄的描述內容以下: 函數