Python的异常处理机制 -- (转)
生活随笔
收集整理的這篇文章主要介紹了
Python的异常处理机制 -- (转)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
當(dāng)你的程序中出現(xiàn)異常情況時(shí)就需要異常處理。比如當(dāng)你打開一個(gè)不存在的文件時(shí)。當(dāng)你的程序中有一些無效的語句時(shí),Python會(huì)提示你有錯(cuò)誤存在。
下面是一個(gè)拼寫錯(cuò)誤的例子,print寫成了Print。Python是大小寫敏感的,因此Python將引發(fā)一個(gè)錯(cuò)誤:>>> Print 'Hello World'File "", line 1Print 'Hello World'^ SyntaxError: invalid syntax>>> print 'Hello World' Hello World
1、try...except語句
try...except語句可以用于捕捉并處理錯(cuò)誤。通常的語句放在try塊中,錯(cuò)誤處理語句放在except塊中。示例如下:#!/usr/bin/python # Filename: try_except.pyimport systry:s = raw_input('Enter something --> ') except EOFError:#處理EOFError類型的異常print '/nWhy did you do an EOF on me?'sys.exit() # 退出程序 except:#處理其它的異常print '/nSome error/exception occurred.'print 'Done' 運(yùn)行輸出如下: $ python try_except.py Enter something --> Why did you do an EOF on me?$ python try_except.py Enter something --> Python is exceptional! Done 說明:每個(gè)try語句都必須有至少一個(gè)except語句。如果有一個(gè)異常程序沒有處理,那么Python將調(diào)用默認(rèn)的處理器處理,并終止程序且給出提示。
2、引發(fā)異常
你可以用raise語句來引發(fā)一個(gè)異常。異常/錯(cuò)誤對象必須有一個(gè)名字,且它們應(yīng)是Error或Exception類的子類。下面是一個(gè)引發(fā)異常的例子:
#!/usr/bin/python #文件名: raising.pyclass ShortInputException(Exception):'''你定義的異常類。'''def __init__(self, length, atleast):Exception.__init__(self)self.length = lengthself.atleast = atleasttry:s = raw_input('請輸入 --> ')if len(s) < 3:raise ShortInputException(len(s), 3)# raise引發(fā)一個(gè)你定義的異常 except EOFError:print '/n你輸入了一個(gè)結(jié)束標(biāo)記EOF' except ShortInputException, x:#x這個(gè)變量被綁定到了錯(cuò)誤的實(shí)例print 'ShortInputException: 輸入的長度是 %d, /長度至少應(yīng)是 %d' % (x.length, x.atleast) else:print '沒有異常發(fā)生.' 運(yùn)行輸出如下: $ python raising.py 請輸入 --> 你輸入了一個(gè)結(jié)束標(biāo)記EOF$ python raising.py 請輸入 --> --> ab ShortInputException: 輸入的長度是 2, 長度至少應(yīng)是 3$ python raising.py 請輸入 --> abc 沒有異常發(fā)生.
3、try...finally語句
當(dāng)你正在讀文件或還未關(guān)閉文件時(shí)發(fā)生了異常該怎么辦呢?你應(yīng)該使用try...finally語句以釋放資源。示例如下:#!/usr/bin/python # Filename: finally.pyimport timetry:f = file('poem.txt')while True: # 讀文件的一般方法line = f.readline()if len(line) == 0:breaktime.sleep(2)#每隔兩秒輸出一行print line, finally:f.close()print 'Cleaning up...closed the file' 運(yùn)行輸出如下: $ python finally.py Programming is fun When the work is done Cleaning up...closed the file Traceback (most recent call last):File "finally.py", line 12, in ?time.sleep(2) KeyboardInterrupt
說明:我們在兩秒這段時(shí)間內(nèi)按下了Ctrl-c,這將產(chǎn)生一個(gè)KeyboardInterrupt異常,我們并沒有處理這個(gè)異常,那么Python將調(diào)用默認(rèn)的處理器,并終止程序,在程序終止之前,finally塊中的語句將執(zhí)行。
轉(zhuǎn)載于:https://www.cnblogs.com/fendou-999/p/3590668.html
總結(jié)
以上是生活随笔為你收集整理的Python的异常处理机制 -- (转)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Reginal2011_Chengdu_
- 下一篇: websocket python爬虫_p