python try 錯誤處理
阿新 • • 發佈:2018-11-24
轉自:https://morvanzhou.github.io/tutorials/python-basic/basic/13-02-try/
原創作者: 莫煩
錯誤處理
輸出錯誤:try:
, except ... as ...:
看如下程式碼
try:
file=open('eeee.txt','r') #會報錯的程式碼
except Exception as e: # 將報錯儲存在 e 中
print(e)
"""
[Errno 2] No such file or directory: 'eeee.txt'
"""
處理錯誤:會使用到迴圈語句。首先報錯:沒有這樣的檔案No such file or directory
y
, 輸入y
以後,系統就會新建一個檔案(要用寫入的型別),再次執行後,檔案中就會寫入ssss
try: file=open('eeee.txt','r+') except Exception as e: print(e) response = input('do you want to create a new file:') if response=='y': file=open('eeee.txt','w') else: pass else: file.write('ssss') file.close() """ [Errno 2] No such file or directory: 'eeee.txt' do you want to create a new file:y ssss #eeee.txt中會寫入'ssss'