Python 例外處理 示範

假設我們要寫一個計算除法的程式碼:
    
dividend = input("請輸入被除數:")
dividend = float(dividend)
divisor = input("請輸入除數:")
divisor = float(divisor)
result = dividend / divisor
print("結果為:", result)
    

上面的程式碼可以執行,但很難真正的交給使用者使用,因為我們會將輸入的內容轉換成浮點數,而使用者輸入的內容是不可預測的,上面至少會出現兩個問題,一個是輸入的不是數字,二是除數等於 0 。

在 Python 中要處理這種例外可以使用 try except。
    
try:
    dividend = input("請輸入被除數:")
    dividend = float(dividend)
except:
    print("輸入錯誤,請重新輸入")
    

如果想要知道取得錯誤資訊可以這樣做:
    
try:
    dividend = input("請輸入被除數:")
    dividend = float(dividend)
except Exception as e:
    print("輸入錯誤,請重新輸入")
    print("錯誤訊息:", e)
    

註:通常我們不會這樣顯示錯誤資訊,使用 print 顯示的錯誤資訊不夠詳細,假設有使用 logging 輸出 log 的話可以直接使用 logging.exception("被除數輸入錯誤") ,透過 logging.exception 可以直接詳細的輸出錯誤訊息。

上面的 Exception 指的是所有的錯誤類別,在大部分的情況下我們不會這樣做,只會針對我們知道的例外做處理,避免出現其他問題而我們誤會了,所以這裡應該只要捕捉 ValueError 就好。也可以使用多個 except 區塊捕捉不同的例外:
    
try:
    dividend = input("請輸入被除數:")
    dividend = float(dividend)
except ValueError as e:
    print("輸入內容必須是數字")
except Exception as e:
    print("發生其他錯誤")
    

在 Python 的例外處理中還有 else 和 finally 。else 是沒有發生例外時執行,而 finally 則是不論有沒有例外一定會執行的區塊
    
try:
    dividend = input("請輸入被除數:")
    dividend = float(dividend)
    print(dividend)
except ValueError as e:
    print("輸入內容必須是數字")
except Exception as e:
    print("發生其他錯誤")
else:
    print("被除數輸入成功")
finally:
    print("程式結束")
    

這裡附上上面的解法:
    
# 輸入除數
dividend = input("請輸入被除數:")
while True:
    try:
        dividend = float(dividend)
        break
    except ValueError:
        print("輸入的不是數字,請重新輸入")
        dividend = input("請輸入被除數:")

# 輸入除數
divisor = input("請輸入除數:")
while True:
    try:
        divisor = float(divisor)
        if divisor == 0:
            print("除數不能為0,請重新輸入")
            divisor = input("請輸入除數:")
        else:
            break
    except ValueError:
        print("輸入的不是數字,請重新輸入")
        divisor = input("請輸入除數:")

# 除法運算
try:
    result = dividend / divisor
    print("結果為:", result)
except Exception as e:
    print("發生其他錯誤")
finally:
    print("程式結束")
    

留言