python 报错继续执行_Python报错不要慌,这三个关键词帮你解决问题!
本文轉載自公眾號“讀芯術”(ID:AI_Discovery)。
寫代碼必然會出現錯誤,而錯誤處理可以針對這些錯誤提前做好準備。通常出現錯誤時,腳本會停止運行,而有了錯誤處理,腳本就可以繼續運行。為此,我們需要了解下面三個關鍵詞:
try:這是要運行的代碼塊,可能會產生錯誤。
except:如果在try塊中出現錯誤,將執行這段代碼。
finally:不管出現什么錯誤,都要執行這段代碼。
現在,我們定義一個函數“summation”,將兩個數字相加。該函數運行正常。
>>>defsummation(num1,num2):
print(num1+num2)>>>summation(2,3)
5
接下來,我們讓用戶輸入其中一個數字,并運行該函數。
>>>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”錯誤出現了,因為我們試圖將數字和字符串相加。請注意,錯誤出現后,后面的代碼便不再執行。所以我們要用到上面提到的關鍵詞,確保即使出錯,腳本依舊運行。
>>try:
summed=2+??3
except:
print("Summation?is?not?ofthe?same?type")Summation?is?not?of?the?same?type
可以看到,try塊出現錯誤,except塊的代碼開始運行,并打印語句。接下來加入“else”塊,來應對沒有錯誤出現的情況。
>>>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
接下來我們用另外一個例子理解。這個例子中,在except塊我們還標明了錯誤類型。如果沒有標明錯誤類型,出現一切異常都會執行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
現在,故意創造一個錯誤,看看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
【責任編輯:趙寧寧 TEL:(010)68476606】
點贊 0
總結
以上是生活随笔為你收集整理的python 报错继续执行_Python报错不要慌,这三个关键词帮你解决问题!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 3d绘图库_python
- 下一篇: css盒子模型_说说css盒子模型