異常處理 try except else


 

 1、try ...except...else結構

                

'''
try ...except...else結構
如果try塊中沒有拋出異常,則執行else塊,如果try中拋出異常,則執行except塊
'''

try:
    a=int(input('請輸入被除數:'))
    b=int(input('請輸入除數:'))
    result=a/b
    print(result)
except BaseException as e:  #將錯誤命名為e
    print('出錯了',e)
else:
    print('計算結果為:',result)

 

 2、try ...except...else...finally結構

'''
try ...except...else...finally結構
如果try塊中沒有拋出異常,則執行else塊,如果try中拋出異常,則執行except塊
'''

try:
    a=int(input('請輸入被除數:'))
    b=int(input('請輸入除數:'))
    result=a/b
    print(result)
except BaseException as e:
    print('出錯了',e)
else:
    print('計算結果為:',result)
finally:                                   # 無論出現什么情況都運行該語句
    print('感謝您的應用')

 

 

3、常見異常

                                                                                      

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM