寫代碼必然會出現錯誤,而錯誤處理可以針對這些錯誤提前做好準備,通常出現錯誤時,腳本會停止運行,而有了錯誤處理,腳本就可以繼續運行,為此,我們需要了解下面三個關鍵詞:
- try:這是要運行的代碼塊,可能會產生錯誤,
- except:如果在try塊中出現錯誤,將執行這段代碼,
- finally:不管出現什么錯誤,都要執行這段代碼,

多人學習python,不知道從何學起,
很多人學習python,掌握了基本語法過后,不知道在哪里尋找案例上手,
很多已經做案例的人,卻不知道如何去學習更加高深的知識,
那么針對這三類人,我給大家提供一個好的學習平臺,免費領取視頻教程,電子書籍,以及課程的源代碼!??¤
QQ群:1057034340
現在,我們定義一個函式“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)
<ipython-input-6-2cc0289b921e> in <module>
----> 1 summation(num1,num2)
2 print("This line will notbe printed because of the error")
<ipython-input-1-970d26ae8592> 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/222881.html
標籤:Python
下一篇:ORM物件關系映射
