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
語句引發異常。你還得指明錯誤/異常的名稱和伴隨異常觸發的異常對象。你可以引發的錯誤或異常應該分別是一個Error
或Exception
類的直接或間接匯出類。
例如:
#!/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>