python程式設計進階之異常處理用法例項分析
本文例項講述了python異常處理用法。分享給大家供大家參考,具體如下:
之前用Java的時候,在容易出錯的地方我們經常使用try…catch或者try…catch…finally來捕捉和顯示異常,在python中很高興地發現它也有這樣的機制。
try..except
這個用於當異常出現的時候,用except從句來處理異常,而不至於程式自動退出。例如,在python裡獲取使用者輸入時,若使用者輸入檔案結束符Ctrl-d,則會引發EOFError檔案結束異常。我們使用try except來處理:
#!/usr/bin/python # Filename: try_except.py import sys try: s = raw_input('Enter something --> ') except EOFError: print '\nWhy did you do an EOF on me?' sys.exit() # exit the program except: print '\nSome error/exception occurred.' # here,we are not exiting the program print 'Done'
我們在執行程式的時候輸入Ctrl-d:
$ python try_except.py
Enter something -->
Why did you do an EOF on me?$ python try_except.py
Enter something --> Python is exceptional!
Done
可以看到,當遇到EOFERROR時,程式執行了except EOFError:中的內容。若出現其他異常,則會執行except:從句中的內容。except後面還可以加else從句,如果沒有發生異常,則執行else從句中的內容。記住,首先,我們要匯入sys模組!!
try.. catch
catch主要用於異常出現的時候抓取異常,方便顯示異常資訊。但是我還沒有見別人用過,找不到例子~所以是不推薦用嘛?誰找到例子可以留言給我^.^
try.. finally
假如你在讀一個檔案的時候,希望在無論異常發生與否的情況下都關閉檔案,該怎麼做呢?這可以使用finally塊來完成。注意,在一個try塊下,你可以同時使用except從句和finally塊。如果你要同時使用它們的話,需要把一個嵌入另外一個。舉個例子(還記得檔案讀寫裡的poem嘛):
#!/usr/bin/python # Filename: finally.py import time try: f = file('poem.txt') while True: # our usual file-reading idiom line = f.readline() if len(line) == 0: break time.sleep(2) print line,finally: f.close() print 'Cleaning up...closed the file'
輸出:
$ 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
我們進行通常的讀檔案工作,但是我有意在每列印一行之前用time.sleep方法暫停2秒鐘。這樣做的原因是讓程式執行得慢一些(Python由於其本質通常執行得很快)。在程式執行的時候,按Ctrl-c中斷/取消程式。
我們可以觀察到KeyboardInterrupt異常被觸發,程式退出。但是在程式退出之前,finally從句仍然被執行,把檔案關閉
用raise引發異常
我們可以使用raise語句 引發 異常,但要指明錯誤/異常的名稱和伴隨異常 觸發的 異常物件。你可以引發的錯誤或異常應該分別是一個Error或Exception類的直接或間接子類。舉個例子:
#!/usr/bin/python # Filename: raising.py class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self,length,atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: s = raw_input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s),3) # Other work can continue as usual here except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException,x: print 'ShortInputException: The input was of length %d,\ was expecting at least %d' % (x.length,x.atleast) else: print 'No exception was raised.'
輸出:
$ python raising.py
Enter something -->
Why did you do an EOF on me?$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2,was expecting at least 3$ python raising.py
Enter something --> abc
No exception was raised.
這裡,我們建立了我們自己的異常型別,其實我們可以使用任何預定義的異常/錯誤。自己定義的異常型別是ShortInputException類。它有兩個域——length是給定輸入的長度,atleast則是程式期望的最小長度。
在except從句中,我們提供了錯誤類和用來表示錯誤/異常物件的變數。這與函式呼叫中的形參和實參概念類似。當觸發raise從句時,會呼叫對應的except從句執行,在這個例子中就引發了except ShortInputException,x 這個錯誤,類似於呼叫。
更多Python相關內容感興趣的讀者可檢視本站專題:《Python入門與進階經典教程》、《Python字串操作技巧彙總》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。