Python高級(jí)-異常處理

The core values of Chinese socialism

異常

  • 廣義上的錯(cuò)誤分為錯(cuò)誤和異常
    • 錯(cuò)誤指的是可以人為避免的
    • 異常是指在語法和邏輯正確的前提下,出現(xiàn)的問題
    • 在Python里,異常是一個(gè)類,可以處理和使用

異常處理

  • 不能保證程序永遠(yuǎn)正確運(yùn)行
  • 必須保證程序在最壞的情況下得到的問題被妥善處理
  • Python的異常處理模塊全部語法:
    try:
        嘗試實(shí)現(xiàn)某個(gè)操作,
        如果沒出現(xiàn)異常,任務(wù)就可以完成
        如果出現(xiàn)異常,將異常從當(dāng)前代碼塊扔出去嘗試解決異常
    
    except 異常類型1:
        解決方案1:用于嘗試在此處處理異常解決問題
    except 異常類型2:
        解決方案3:用于嘗試在此處處理異常解決問題
    
    except (異常類型3, 異常類型4):
        解決方案:針對(duì)多個(gè)異常使用相同的處理方式
    
    except :
        解決方案:所有異常的解決方案
        
    else:
        如果沒有出現(xiàn)異常,將會(huì)執(zhí)行此處代碼
        
    finally:
        管你有沒有錯(cuò)誤都要執(zhí)行的代碼
        
    
# 簡單異常案例
try:
    num = int(input("Plz input your number:"))
    rst = 100/num
    print("result = {}".format(rst))
except:
    print("你TM輸?shù)纳锻嬉猓。。?)
    
    #exit()退出程序
    exit()
Plz input your number:0
你TM輸?shù)纳锻嬉猓。。?

ERROR:root:Invalid alias: The name clear can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name more can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name less can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name man can't be aliased because it is another magic command.
# 簡單異常案例
#給出提示信息
try:
    num = int(input("Plz input your number:"))
    rst = 100/num
    print("result = {}".format(rst))
    
# 捕獲異常后,把異常實(shí)例化,出錯(cuò)信息在實(shí)例化里
# 注意以下寫法
# 以下語句是捕獲ZeroDivisionError異常并實(shí)例化實(shí)例e
# 在異常類繼承關(guān)系中,越是子類的異常,越要往前放,越是父類的異常,越要往后放

# 在處理異常的時(shí)候,一旦攔截到某一個(gè)異常,則不再繼續(xù)往下查看except,有finally則執(zhí)行finally語句塊,否則就執(zhí)行下一個(gè)大語句
except ZeroDivisionError as e:
    print("你TM輸?shù)纳锻嬉猓。。?)
    print(e)
    exit()
    
except NameError as e:
    print("名字起錯(cuò)了")
    print(e)
    exit()
    
except AttributeError as e:
    print("屬性有問題")
    print(e)
    exit()

# 所有異常都是繼承自Exception,任何異常都會(huì)攔截  
# 而且一定是最后一個(gè)except
except Exception as e:
    print("不知道什么錯(cuò)!")
    print(e)
    exit()
    
finally:
    print("我肯定會(huì)被執(zhí)行的")
    
Plz input your number:0
你TM輸?shù)纳锻嬉猓。。?division by zero
我肯定會(huì)被執(zhí)行的


ERROR:root:Invalid alias: The name clear can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name more can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name less can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name man can't be aliased because it is another magic command.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容