python中提供了很多不同形式的異常處理結構,其基本思路都是先嘗試執行代碼,再處理可能發生的錯誤。
try…except…
在python異常處理結構中,try…except…使用最為頻繁,其中try子句中的代碼塊為可能引發異常的語句,except子句用來捕獲相應的異常。
例如,在使用學校的學生成績系統錄入每科成績時,要求輸入0~100的整數,而不接受其他類型的數值,如果輸入的值超過0~100這一范圍,則會給出提示。
#! /usr/bin/python
#coding:utf-8
mathScore = input('數學成績')
try:mathScore = int(mathScore)if (0<=mathScore<=100):print("輸入的數學成績為:",mathScore)else:print('輸入的數值有誤')
except Exception as e:print('輸入的數值有誤')
運行結果為
try…except…else…
如果try代碼的子句出現了異常且該異常被except捕獲,則可以執行相應的異常處理代碼,此時就不會執行else的子句;如果try中的代碼沒有拋出異常,則繼續執行else子句
#! /usr/bin/python
#coding:utf-8
mathScore = input('數學成績:')
try:mathScore = int(mathScore)
except Exception as e:print('輸入的數值有誤')
else:if (0<=mathScore<=100):print("輸入的數學成績為:",mathScore)else:print('輸入的數值有誤')
運行結果:
try … except…finally…
無論try子句是否正常執行,finally子句中的代碼塊總會得到執行。在日常開發過程中,該結構通常用來做清理工作,釋放子句中申請的資源。
例如,輸入兩個數值a,b進行除法運算,并輸出最終結果。
#! /usr/bin/python
#coding:utf-8
a = int(input('a:'))
b = int(input('b:'))
try:div = a / bprint(div)except Exception as e:print('The second parameter cannot be 0.')
finally:print('運行結束!')