1. 程式人生 > >【再回首Python之美】【異常處理】try-except

【再回首Python之美】【異常處理】try-except

使用方法直接跳看:推薦使用的異常處理流程;推薦的內建函式的封裝函式

異常處理必要性

為了保證程式的健壯性,將可能出現異常退出的程式碼用try……except來處理

捕獲異常的各種方法

    1.捕獲所有異常

print "\r\n=======try-except========="
try:
    open('unexistFile')
except:
    print "failed to open."

    2.捕獲特殊異常,如ctrl+c等

    KeyboardInterrupt和SystemExit,是與Exception平級的異常。

print '\r\n======try-except (KeyboardInterupt, SystemExit)======'
try:
    while 1:
        pass
except (KeyboardInterrupt, SystemExit):#ctrl+c等導致app退出異常
    print 'app will exit, handle app exitence.'

    3.捕獲具體異常,1/0等

print "\r\n======try-except ZeroDivisionError,e======="
try:
    1/0 #除數為零
except ZeroDivisionError, e:
    print 'ZeroDivisionError:',e

    4.捕獲多個具體的異常

#try-except (E1, E2,……En)[,e]:捕獲多個異常
print '\r\n======try-except (E1, E2,……En)[,e]======'
try:
    1/0
except (NameError,ZeroDivisionError),e:
    print repr(e)

    5.待追加

簡單示例程式碼

#ex_except.py

def dumpFile_withExcept(path):
    try:
        f = file(path)
        print 'Succeed open file'
        f.close()
    except:
        print 'Failed open file, file not exists.'
        return False
    return True

def dumpFile_nonExcept(path):
    f = file(path)
    f.close()
    
#test
dumpFile_withExcept('non-exist.txt')
dumpFile_nonExcept('non-exist.txt')
編譯執行


可知

    有了try……excepty異常捕捉處理的dumpFile_withExcept函式開啟不存在檔案時,try丟擲異常,然後由except捕獲並執行except程式碼塊。

    沒有異常捕捉處理的dumpFile_nonExcept函式開啟不存在檔案時,由程式直接退出並給出IOError等資訊。

示例程式碼(追加)

#ex_try-except.py
self_file = __file__

#try-except,捕獲所有異常
print "\r\n=======try-except========="
try:
    open('unexistFile')
except:
    print "failed to open."


#try-except + trceback,列印異常堆疊以及錯誤資訊
print "\r\n=======traceback + try-except========="
import traceback #use traceback module
try:
    open('unexistFile')
except:
    print 'traceback.print_exc():',traceback.print_exc()
    print 'traceback.format_exc():\n%s' % traceback.format_exc()


#try-except Exception,e,捕獲所有異常
print '\r\n======try-except Exception,e======'
try:
    open('unexistFile')
except Exception,e:
    print 'ErrorInfo:',e
    print 'ErrorInfo:',e.message
    print 'ErrorInfo:',str(e)
    print "ErrorInfo:",repr(e)
    

#try-except Exception,(errCode, errMsg),捕獲所有異常以及具體錯誤碼
print '\r\n======try-except Exception,(errCode, errMsg)======'
import errno #use errno module
try:
    open('unexistFile')
except Exception,(errCode,errMsg):
    if errCode == errno.ENOENT:
        print 'failed to open, no such file.'
    elif errCode == errno.EPERM:
        print 'failed to open, permission denied'
    else:
        print errMsg

        
#try-except ErrorType, e,捕獲具體異常
print '\r\n======try-except (KeyboardInterupt, SystemExit)======'
try:
    while 1:
        pass
except (KeyboardInterrupt, SystemExit):#ctrl+c等導致app退出異常
    print 'app will exit, handle app exitence.'
        
print "\r\n======try-except NameError,e======="
try:
    print unexistVal #訪問一個未申明的變數
except NameError, e:
    print repr(e)

print "\r\n======try-except ZeroDivisionError,e======="
try:
    1/0 #除數為零
except ZeroDivisionError, e:
    print 'ZeroDivisionError:',e

print "\r\n======try-except IndexError,e======="
try:
   lst = []
   print lst[99] #請求的索引超出序列範圍
except IndexError,e:
    print 'IndexError:',e.message

print "\r\n======try-except KeyError,e======="
try:
    adct = {'Tom':25, 'John':18, 'Ann':20}
    print adct['Kitty'] #請求一個不存在的字典關鍵字
except KeyError,e:
    print 'KeyError:',e

print "\r\n======try-except IOError,e======="
try:
    f = open('unexistFile') #開啟一個不存在的檔案或目錄
except IOError,e:
    print 'IOError:',e

print "\r\n======try-except AttributeError,e======="
try:
    class Car(object):
        pass
    car = Car()
    print car.color #訪問未知的物件屬性
except AttributeError, e:
    print 'AttributeError:',e


#try-except-……-except,捕獲具體異常並具體處理
print '\r\n=====try-except-……-except=========='
try:
    1/0
except NameError, e:
    print 'NameError:',e
except ZeroDivisionError, e: #由此except抓獲1/0丟擲的異常
    print 'ZeroDivisionError:',e    
except IndexError,e:
    print 'IndexError:',e
except KeyError,e:
    print 'KeyError:',e
except IOError,e:
    print 'IOError:',e
except AttributeError, e:
    print 'AttributeError:',e
except:#預設except必須作為最後一個except
    print 'Unknown Error:',errno


#(start)推薦使用的異常處理流程
print '\r\n=====try-except======'

import errno     #use errno module
import traceback #use traceback module

def handleException(errCode, errMsg):
    if errCode == errno.ENOENT:
        print 'failed to open, no such file.'
    elif errCode == errno.EPERM:
        print 'failed to open, permission denied'
    else:
        print errMsg

try:
    open('unexistFile')
except Exception,(errCode,errMsg):
    print traceback.format_exc()
    handleException(errCode, errMsg)

#(end)推薦使用的異常處理流程

#(start)推薦的內建函式的封裝函式
print '\r\n======define safe function====='
import errno #use errno module
import traceback #use traceback module

def safe_open(file_path, mode):
    try:
        ret = open(file_path, mode)
    except Exception,(errCode, errMsg):
        print traceback.format_exc()
        if errCode == errno.ENOENT:
            ret = 'ErrorInfo:failed to open, no such file.'
        elif errCode == errno.EPERM:
            ret = 'ErrorInfo:failed to open, permission denied.'
        else:
            ret = errMsg
    return ret
         
f = safe_open('unexistFile', 'r')
#(end)推薦的內建函式的封裝函式

print '\r\nexit %s' % self_file

執行結果:

>>> 
=================== RESTART: C:\Python27\ex_try-except.py ===================


=======try-except=========
failed to open.


=======traceback + try-except=========
traceback.print_exc():Traceback (most recent call last):
  File "C:\Python27\ex_try-except.py", line 16, in <module>
    open('unexistFile')
IOError: [Errno 2] No such file or directory: 'unexistFile'
 None
traceback.format_exc():
Traceback (most recent call last):
  File "C:\Python27\ex_try-except.py", line 16, in <module>
    open('unexistFile')
IOError: [Errno 2] No such file or directory: 'unexistFile'



======try-except Exception,e======
ErrorInfo: [Errno 2] No such file or directory: 'unexistFile'
ErrorInfo: 
ErrorInfo: [Errno 2] No such file or directory: 'unexistFile'
ErrorInfo: IOError(2, 'No such file or directory')


======try-except Exception,(errCode, errMsg)======
failed to open, no such file.


======try-except (KeyboardInterupt, SystemExit)======
app will exit, handle app exitence.


======try-except NameError,e=======
NameError("name 'unexistVal' is not defined",)


======try-except ZeroDivisionError,e=======
ZeroDivisionError: integer division or modulo by zero


======try-except IndexError,e=======
IndexError: list index out of range


======try-except KeyError,e=======
KeyError: 'Kitty'


======try-except IOError,e=======
IOError: [Errno 2] No such file or directory: 'unexistFile'


======try-except AttributeError,e=======
AttributeError: 'Car' object has no attribute 'color'


=====try-except-……-except==========
ZeroDivisionError: integer division or modulo by zero


=====try-except======
Traceback (most recent call last):
  File "C:\Python27\ex_try-except.py", line 132, in <module>
    open('unexistFile')
IOError: [Errno 2] No such file or directory: 'unexistFile'

failed to open, no such file.


======define safe function=====
Traceback (most recent call last):
  File "C:\Python27\ex_try-except.py", line 146, in safe_open
    ret = open(file_path, mode)
IOError: [Errno 2] No such file or directory: 'unexistFile'



exit C:\Python27\ex_try-except.py
>>> 

(end)