例外是使用try-except-else程式區塊來處理,try區塊的程式碼是要放可能引起例外的程式碼,如果try的程式區塊執行無誤的話,就會跳到else區塊,而except區塊是放出現指定例外時要處理的程式碼
以下的範例是處理ZeroDivisionError例外的try-except程式碼
範例如下 :
try:
print(1/0)
except ZeroDivisionError:
print("You can't divide by zero")
上面的程式碼如果try區塊沒問題的話就會跳過except區塊,如果try區塊區出錯時就會進入except區塊檢測是否為這個錯誤,並執行其中的程式碼
輸出結果 :
You can't divide by zero
以下的範例是處理ZeroDivisionError例外的try-except-else程式碼
範例如下 :
while True:
first=input("First number :")
second=input("Second number :")
try:
ans=int(first)/int(second) # 因為input都是字串所以要轉int才能相除
except ZeroDivisionError:
print("You can't divide by zero")
else:
print(ans) # 若沒有出錯就印出兩個值相除
break # 跳出迴圈
輸出結果 :
First number :5
Second number :0
You can't divide by zero
First number :4
Second number :0
You can't divide by zero
First number :6
Second number :3
2.0
以下的範例是處理FileNotFoundError例外的try-except-else程式碼,當我們找不到檔案時會印出一行訊息告知使用者檔案找不到,找的到檔案的話就讀取檔案內容,然後到else區塊讓使用者輸入要找的字,然後計算總共在alice.txt檔中出現幾次
範例如下 :
filename="alice.txt"
try:
with open(filename) as file:
contents=file.read()
except FileNotFoundError: # 如果找不到檔案會執行這個區塊
msg="Sorry,the file "+filename+" does not exist"
print(msg)
else: # 找到檔案會執行這個區塊
find=input("find the word :")
print(contents.count(find))
↓ alice.txt檔
ALICE was beginning to get very tired of sitting by
her sister on the bank and of having nothing to do:
once or twice she had peeped into the book her sister
was reading, but it had no pictures or conversations
in it, "and what is the use of a book," thought Alice,
"without pictures or conversations?'
輸出結果 :
find the word :the
3
p.s 今天寫的程式碼碰到錯誤訊息時都會在except區塊印出一條訊息告知我們有錯,當我們想要出錯時無聲無息地繼續執行,也不會讓程式碼跑不下去時,我們可以用pass,只要在except區塊內放pass就好
範例如下 :
filename="alice.txt"
try:
with open(filename) as file:
contents=file.read()
except FileNotFoundError: # 如果找不到檔案會執行這個區塊
pass # 出錯時直接略過這個區塊
else: # 找到檔案會執行這個區塊
find=input("find the word :")
print(contents.count(find))
附上排版較精美的
HackMD網址:https://hackmd.io/UcV0wxJSRT-n8Tbu3JZ1mw?both
資料來源:<<python程式設計的樂趣>>-Eric Matthes著/H&C譯