Python筆記(10)

來源:互聯網
上載者:User

Python中的異常

 

當你的程式中出現某些異常的狀況的時候,異常就發生了。

 

一.處理異常

我們可以使用try..except語句來處理異常。我們把通常的語句放在try-塊中,而把我們的錯誤處理語句放在except-塊中。

例如:

#!/usr/bin/python<br /># Filename: try_except.py</p><p>import sys</p><p>try:<br /> s = raw_input('Enter something --> ')<br />except EOFError:<br /> print '\nWhy did you do an EOF on me?'<br /> sys.exit() # exit the program<br />except:<br /> print '\nSome error/exception occurred.'<br /> # here, we are not exiting the program</p><p>print 'Done' </p><p>

輸出為:

$ python try_except.py<br />Enter something --><br />Why did you do an EOF on me?</p><p>$ python try_except.py<br />Enter something --> Python is exceptional!<br />Done</p><p>

二.引發異常

你可以使用raise語句引發異常。你還得指明錯誤/異常的名稱和伴隨異常觸發的異常對象。你可以引發的錯誤或異常應該分別是一個ErrorException類的直接或間接匯出類。

例如:

#!/usr/bin/python<br /># Filename: raising.py</p><p>class ShortInputException(Exception):<br /> '''A user-defined exception class.'''<br /> def __init__(self, length, atleast):<br /> Exception.__init__(self)<br /> self.length = length<br /> self.atleast = atleast</p><p>try:<br /> s = raw_input('Enter something --> ')<br /> if len(s) < 3:<br /> raise ShortInputException(len(s), 3)<br /> # Other work can continue as usual here<br />except EOFError:<br /> print '\nWhy did you do an EOF on me?'<br />except ShortInputException, x:<br /> print 'ShortInputException: The input was of length %d, \<br /> was expecting at least %d' % (x.length, x.atleast)<br />else:<br /> print 'No exception was raised.' </p><p>

輸出為:

$ python raising.py<br />Enter something --><br />Why did you do an EOF on me?</p><p>$ python raising.py<br />Enter something --> ab<br />ShortInputException: The input was of length 2, was expecting at least 3</p><p>$ python raising.py<br />Enter something --> abc<br />No exception was raised. </p><p>

三.try..finally

假如你在讀一個檔案的時候,希望在無論異常發生與否的情況下都關閉檔案,該怎麼做呢?這可以使用finally塊來完成。注意,在一個try塊下,你可以同時使用except從句和finally塊。如果你要同時使用它們的話,需要把一個嵌入另外一個。

#!/usr/bin/python<br /># Filename: finally.py</p><p>import time</p><p>try:<br /> f = file('poem.txt')<br /> while True: # our usual file-reading idiom<br /> line = f.readline()<br /> if len(line) == 0:<br /> break<br /> time.sleep(2)<br /> print line,<br />finally:<br /> f.close()<br /> print 'Cleaning up...closed the file' </p><p>

輸出為:

$ python finally.py<br />Programming is fun<br />When the work is done<br />Cleaning up...closed the file<br />Traceback (most recent call last):<br /> File "finally.py", line 12, in ?<br /> time.sleep(2)<br />KeyboardInterrupt </p><p>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.