python 报错继续执行_Python报错不要慌,这三个关键词帮你解决问题!
本文轉(zhuǎn)載自公眾號(hào)“讀芯術(shù)”(ID:AI_Discovery)。
寫代碼必然會(huì)出現(xiàn)錯(cuò)誤,而錯(cuò)誤處理可以針對(duì)這些錯(cuò)誤提前做好準(zhǔn)備。通常出現(xiàn)錯(cuò)誤時(shí),腳本會(huì)停止運(yùn)行,而有了錯(cuò)誤處理,腳本就可以繼續(xù)運(yùn)行。為此,我們需要了解下面三個(gè)關(guān)鍵詞:
try:這是要運(yùn)行的代碼塊,可能會(huì)產(chǎn)生錯(cuò)誤。
except:如果在try塊中出現(xiàn)錯(cuò)誤,將執(zhí)行這段代碼。
finally:不管出現(xiàn)什么錯(cuò)誤,都要執(zhí)行這段代碼。
現(xiàn)在,我們定義一個(gè)函數(shù)“summation”,將兩個(gè)數(shù)字相加。該函數(shù)運(yùn)行正常。
>>>defsummation(num1,num2):
print(num1+num2)>>>summation(2,3)
5
接下來,我們讓用戶輸入其中一個(gè)數(shù)字,并運(yùn)行該函數(shù)。
>>>num1=2
>>>num2=input("Enter?number:?")
Enter?number:?3>>>summation(num1,num2)>>>print("Thisline?will?not?be?printed?because?of?the?error")
---------------------------------------------------------------------------
TypeError????????????????????????????????Traceback?(most?recent?call?last)
in
---->1?summation(num1,num2)
2?print("This?line?will?notbe?printed?because?of?the?error")
in?summation(num1,?num2)
1?def?summation(num1,num2):
---->2?????print(num1+num2)
TypeError:?unsupported?operand?type(s)?for?+:??int??and??str
“TypeError”錯(cuò)誤出現(xiàn)了,因?yàn)槲覀冊(cè)噲D將數(shù)字和字符串相加。請(qǐng)注意,錯(cuò)誤出現(xiàn)后,后面的代碼便不再執(zhí)行。所以我們要用到上面提到的關(guān)鍵詞,確保即使出錯(cuò),腳本依舊運(yùn)行。
>>try:
summed=2+??3
except:
print("Summation?is?not?ofthe?same?type")Summation?is?not?of?the?same?type
可以看到,try塊出現(xiàn)錯(cuò)誤,except塊的代碼開始運(yùn)行,并打印語句。接下來加入“else”塊,來應(yīng)對(duì)沒有錯(cuò)誤出現(xiàn)的情況。
>>>try:
summed=2+?3
except:
print("Summation?is?not?ofthe?same?type")
else:
print("There?was?no?errorand?result?is:?",summed)There?was?no?error?and?result?is:??5
接下來我們用另外一個(gè)例子理解。這個(gè)例子中,在except塊我們還標(biāo)明了錯(cuò)誤類型。如果沒有標(biāo)明錯(cuò)誤類型,出現(xiàn)一切異常都會(huì)執(zhí)行except塊。
>>>try:
f=open(?test?,?w?)
f.write("This?is?a?testfile")
except?TypeError:
print("There?is?a?typeerror")
except?OSError:
print("There?is?an?OSerror")
finally:
print("This?will?print?evenif?no?error")This?will?print?even?if?no?error
現(xiàn)在,故意創(chuàng)造一個(gè)錯(cuò)誤,看看except塊是否與finally塊共同工作吧!
>>>try:
f=open(?test?,?r?)
f.write("This?is?a?testfile")
except?TypeError:
print("There?is?a?typeerror")
except?OSError:
print("There?is?an?OSerror")
finally:
print("This?will?print?evenif?no?error")There?is?an?OS?error
This?will?print?even?if?no?error
【責(zé)任編輯:趙寧寧 TEL:(010)68476606】
點(diǎn)贊 0
總結(jié)
以上是生活随笔為你收集整理的python 报错继续执行_Python报错不要慌,这三个关键词帮你解决问题!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 3d绘图库_python
- 下一篇: css盒子模型_说说css盒子模型