3.5異常處理
1.bug
語法錯誤
運行時錯誤
語義錯誤
2.Debug
3.異常處理
對于運行時可能產(chǎn)生的錯誤凌外,我們可以提前在程序中操作
這樣做有兩個可能的目的:
(1)讓程序終止前進行更多的操作,比如提供更多關(guān)于錯誤的信息
(2)讓程序在犯錯后依然能運行下去
異常處理還能提高程序容錯性,例如
while True:
inputStr = input("Please input a number:") #等待輸入
try:
num = float(inputStr)
print("Input number:",num)
print("result:",10/num)
except ValueError:
print("Illegal input. Try Again.")
except ZeroDivisionError:
print("Illegal devision by zero. Try Again.")
Please input a number:2
Input number: 2.0
result: 5.0
Please input a number:-2
Input number: -2.0
result: -5.0
Please input a number:11
Input number: 11.0
result: 0.9090909090909091
Please input a number:-11
Input number: -11.0
result: -0.9090909090909091
Please input a number:0
Input number: 0.0
Illegal devision by zero. Try Again.
Please input a number:p
Illegal input. Try Again.
Please input a number:
需要異常處理的程序包裹在try結(jié)構(gòu)中审姓,而except說明了當(dāng)特定錯誤發(fā)生時
程序該如何應(yīng)對,程序中蔬捷,input()是一個內(nèi)置函數(shù)企巢,用來接收命令行的輸入
而float()函數(shù)則用于把其他類型的數(shù)據(jù)轉(zhuǎn)換為浮點數(shù)
如果輸入的是一個字符串,如“p”丑念,則無法轉(zhuǎn)換為浮點數(shù)
并觸發(fā)ValueError涡戳,而相應(yīng)的except就會運行隸屬于它的程序
如果輸入的是0,那么除法的分母為0脯倚,將觸發(fā)ZeroDivisionError
這兩種錯誤都是由預(yù)設(shè)的程序處理的渔彰,所以程序運行不會終止
如果沒有發(fā)生異常,比如輸入2推正,那么try部分正常運行恍涂,except部分被跳過
異常處理完整語法為:
try:
...
except exception1:
...
except exception2:
...
else:
...
finally:
...
如果try中有異常發(fā)生時,將執(zhí)行異常歸屬植榕,執(zhí)行except
異常層層比較再沧,看是否是exception1,exception2...
直到找到其歸屬尊残,執(zhí)行相應(yīng)except中的語句
如果try中沒有異常炒瘸,那么except部分跳過,執(zhí)行else中的語句
finally是無論是否發(fā)生異常寝衫,最后都要做的事
如果except后面沒有任何參數(shù)顷扩,那么表示所有的exception都交給這段程序處理
例如:
while True:
inputStr = input("Please input a number:")
try:
num = float(inputStr)
print("Input number:",num)
print("result:",10/num)
except:
print("Something Wrong.Try Again.")
Please input a number:p
Something Wrong.Try Again.
Please input a number:2.5
Input number: 2.5
result: 4.0
Please input a number:3.5564
Input number: 3.5564
result: 2.8118321898549095
Please input a number:
如果無法將異常交給合適對象,那么異常將繼續(xù)向上層拋
直到被捕捉或者造成主程序報錯竞端,例如:
def test_func()
try:
m = 1/0
except ValueError:
print("Catch ValueError in the sub-function")
try:
test_func()
except ZeroDivisionError:
print("Catch error in the main program")
Catch error in the main program
子程序的try...except...結(jié)構(gòu)無法處理相應(yīng)的除以0的錯誤
所以錯誤被拋給上層程序