當程式執行的時候,可能會出現一些異常現象,這個可能是會存在的。例如,你在讀檔案的時候,而那個檔案不存在。此時,我們可以用異常來處理。
1. 錯誤
我們來做個簡單的測試,我們故意把print方法寫出Print。
>>> Print("Hello world")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
Print("Hello world")
NameError: name 'Print' is not defined
>>>
系統會拋出NameError異常。
2. try..except
我們可以用try..except處理異常。
try: f = open("test.txt") f.close()except(IOError): print("The file is not exist.")except: print("Some error occurred.")print("Done")
運行結果:
The file is not exist.
Done
3. 引發異常
你可以用raise語句來引發異常。我們先自訂一個ShortInputError異常,需要繼承Exception類。
class ShortInputError(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleasttry: s = input("Enter something -->") if len(s) < 3: raise(ShortInputError(len(s), 3)) #Other work can continue as usual hereexcept(EOFError): print("Why did you do an EOF on me?")except ShortInputError as e: print("ShortInputError: The input was of length %d, \was expecting at least %d" % (e.length, e.atleast))else: print("No exception was raised.")
輸入兩個字元運行結果:
>>>
Enter something -->tr
ShortInputError: The input was of length 2, was expecting at least 3
>>>
輸入三個字元以上運行結果:
>>>
Enter something -->test
No exception was raised.
>>>
4. try..finally
假如你在讀一個檔案的時候,希望在無論異常發生與否的情況下都關閉檔案,該怎麼做呢?這可以使用finally塊來完成。注意,在一個try塊下,你可以同時使用except從句和finally塊。如果你要同時使用它們的話,需要把一個嵌入另外一個。
import timetry: f = open("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")
運行結果:
>>>
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Cleaning up...closed the file
>>>
def divide(x, y): try: result = x/ y except ZeroDivisionError: print("Division by zero!") else: print("result is", result) finally: print("executing finally clause")
測試結果:
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
Division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
divide("2", "1")
File "<pyshell#10>", line 3, in divide
result = x/ y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
>>>