天天看點

Python學習-17.Python中的錯誤處理(二)

錯誤是多種多樣的,在 except 語句中,可以捕獲指定的異常

修改代碼如下:

1 import io
 2 
 3 path = r''
 4 mode = 'w'
 5 
 6 try:
 7     file = open(path,mode)
 8     str = file.read()
 9     print(str)
10 except FileNotFoundError as e:
11     print(e)
12 except io.UnsupportedOperation as e:
13     print(e)
14 finally:
15     print('end')      

那麼,現在隻有在 path 和 mode 都正确的情況下,才會輸出檔案内容,而錯誤的話,則會輸出錯誤的資訊。