Python學習筆記(十一)—— 異常處理

異常處理
python中的異常處理使用try…except…else語句,形式如下:

try:
    語句塊
except ERROR1:
    語句塊
except ERROR2:
    語句塊
...
else 

自定義異常類型
通過定義Exception類(或BasException)的子類來自己定義用戶異常類型,使用raise語句來拋出異常
示例如下

class UserException(Exception):
    def __init__(self,length,adjust):
        Exception.__init__(self)
        self.length =length
        self.doc = adjust
try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise UserException(len(text), 3)
    # 拋出異常對象,其他工作能在此處繼續正常運行
except UserException as ex:
    # except語句接收類對象,並記爲ex,類似於實參與形參的區別,後續通過ex引用該對象
    print(('ShortInputException: The input was ' +\
    '{0} long, expected at least {1}')\
    .format(ex.length, ex.doc))
else:
    print('No exception was raised.')

finally語句
如果希望無論有沒有異常拋出都執行某些操作,則可以在最後添加finally語句塊,示例如下:

class UserException(BaseException):
    def __init__(self,length,adjust):
        BaseException.__init__(self)
        self.length =length
        self.doc = adjust
import sys
import time
f = None
try:
    f = open("poem.txt")
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end='')
        sys.stdout.flush()
        text = input('Enter something --> ')
        if len(text) < 3:
            raise UserException(len(text), 3)
        # 爲了確保程序能運行一段時間
        time.sleep(2)
except IOError:
    print("Could not find file poem.txt")
except UserException as ex:
    print(('ShortInputException: The input was ' +\
    '{0} long, expected at least {1}')\
    .format(ex.length, ex.doc))
else:
    print('successfully finished')
finally:
    if f:
        f.close()
    print("(Cleaning up: Closed the file)")

with語句
上述例子中的finally語句塊主要用來保證文件打開後能夠被正確的關閉,在python中提供with語句可以直接實現這一功能,即with 語句可以保證諸如文件之類的對象在使用完之後一定會正確的執行他的清理方法:。
示例:

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")

等價於

try:
    f = open("myfile.txt")
    for line in f
        print(line, end="")
finally:
    f.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章