Python中的異常處理(不定時(shí)更新)

1 異常的定義

程序運(yùn)行期檢測(cè)到的錯(cuò)誤被稱為異常exception,它以錯(cuò)誤信息的形式展現(xiàn)。python提供了異常處理機(jī)制(exception-handling machnism),采用異常對(duì)象exception objects來(lái)代表異常情況。當(dāng)出現(xiàn)錯(cuò)誤時(shí),通過(guò)調(diào)用Traceback棧的形式將異常對(duì)象拋出/提出(raise),同時(shí)程序停止運(yùn)行。
為保證程序出錯(cuò)后可繼續(xù)執(zhí)行,需要對(duì)錯(cuò)誤進(jìn)行捕捉和處理。因?yàn)楫?dāng)使用者使用程序時(shí),程序出現(xiàn)異常后終止并報(bào)出tracebacks顯然是不合理的(他們可能并不懂哪里出了問(wèn)題);更危言聳聽(tīng)一點(diǎn),心懷不軌的人可能會(huì)根據(jù)traceback信息知悉程序存在的漏洞并加以破壞。
舉例:輸入兩個(gè)數(shù)字,打印二者的商。當(dāng)作為除數(shù)的數(shù)字為0時(shí),會(huì)提出異常對(duì)象ZeroDivisionError,它的前面指明了產(chǎn)生異常的位置:

num1 = int(input("Enter the first number : "))
num2 = int(input("Enter the second number : "))
print(num1/num2)
------------------------------在終端中運(yùn)行------------------------------
Enter the first number : 10
Enter the second number : 0
Traceback (most recent call last):
  File "e:/PYTHON_EX/test.py", line 11, in <module>
    print(num1/num2)
ZeroDivisionError: division by zero

2 基本語(yǔ)法

2.1 try-except語(yǔ)句

如果可預(yù)見(jiàn)某類異常會(huì)發(fā)生,可采用 try-except 語(yǔ)句進(jìn)行處理,將可能出錯(cuò)的語(yǔ)句“包裹”起來(lái)。,它的基本語(yǔ)法如下:

try:
    try_statements # Python tries to run the code here.
except some_exception1:
    e1_statements # if the code results in a particular kind of exception, run the statements here.
except some_exception2:
    e2_statements # if the code results in a particular kind of exception, run the statements here.

some_exception可以是單個(gè)異常類型,或是由多個(gè)異常類型組成的元祖。
執(zhí)行流程:

  1. 如果try后的語(yǔ)句運(yùn)行無(wú)誤,那么python繼續(xù)執(zhí)行 try-except 后面的語(yǔ)句;
  2. 如果try后的語(yǔ)句運(yùn)行出現(xiàn)錯(cuò)誤,那么python查找與錯(cuò)誤匹配的except語(yǔ)句塊(可以有多個(gè)):
    • 匹配成功,在運(yùn)行該except語(yǔ)句塊中的語(yǔ)句(如進(jìn)行較友好的錯(cuò)誤提示)后繼續(xù)執(zhí)行 try-except 后面的語(yǔ)句;
    • 匹配失敗,提出異常,程序終止。

在前面例子基礎(chǔ)上增加 try-except 語(yǔ)句,如下:

try:
    num1 = int(input("Enter the first number : "))
    num2 = int(input("Enter the second number : "))
    print(num1/num2)
except ZeroDivisionError:
    print("The second number shouldn't be zero.")
except ValueError:
    print("Number required.")
------------------------------在終端中運(yùn)行------------------------------
Enter the first number : 10
Enter the second number : 0
The second number shouldn't be zero.
或
Enter the first number : a
Number required.

2.2 try-except-else語(yǔ)句

try后的語(yǔ)句執(zhí)行無(wú)誤,則依次執(zhí)行else后的語(yǔ)句、try-except-else后的語(yǔ)句。else后的語(yǔ)句的執(zhí)行依賴于try后語(yǔ)句的成功執(zhí)行。
語(yǔ)句執(zhí)行流程:

  1. 如果try后的語(yǔ)句運(yùn)行無(wú)誤,那么python先運(yùn)行else后的語(yǔ)句,再執(zhí)行 try-except-else 后面的語(yǔ)句;
  2. 如果try后的語(yǔ)句運(yùn)行出現(xiàn)錯(cuò)誤,那么python查找與錯(cuò)誤匹配的except語(yǔ)句塊:
    • 匹配成功,在運(yùn)行該except語(yǔ)句塊中的語(yǔ)句(如進(jìn)行較友好的錯(cuò)誤提示)后繼續(xù)執(zhí)行 try-except 后面的語(yǔ)句;
    • 匹配失敗,提出異常,程序終止。

如下所示:

try:
    num1 = int(input("Enter the first number : "))
    num2 = int(input("Enter the second number : "))
    answer = num1/num2
except ZeroDivisionError:
    print("The second number should not be zero.")
except ValueError:
    print("A number is required.")
else:
    print("The answer is {}.".format(answer))
print("It ends here.")
------------------------------在終端中運(yùn)行------------------------------
Enter the first number : 10
Enter the second number : 5
The answer is 2.0.
It ends here.

2.3 try-except-else-finally

完全體出現(xiàn)。finally后的語(yǔ)句無(wú)論如何都會(huì)執(zhí)行。不再詳述。

2.4 raise語(yǔ)句

使用raise語(yǔ)句是,后面不跟參數(shù)可以報(bào)出預(yù)期外的異常;raise后跟上某種異常類型可在出現(xiàn)錯(cuò)誤時(shí)報(bào)出該異常。

try:
    1/a
except ZeroDivisionError:
    print("The second number should not be zero.")
except:
    raise
------------------------------在終端中運(yùn)行------------------------------
NameError: name 'a' is not defined
try:
    1/a
except ZeroDivisionError:
    print("The second number should not be zero.")
except:
    raise FileNotFoundError # 舉例
------------------------------在終端中運(yùn)行------------------------------
Traceback (most recent call last):
  File "e:/PYTHON_EX/test.py", line 6, in <module>
    raise FileNotFoundError
FileNotFoundError
最后編輯于
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • python提供了兩個(gè)非常重要的功能來(lái)處理python程序在運(yùn)行中出現(xiàn)的異常和錯(cuò)誤。你可以使用該功能來(lái)調(diào)試pyth...
    _寧采臣閱讀 1,095評(píng)論 0 10
  • (1)午夜的街道,街燈、穿梭的汽車和霧氣籠罩的街道。這是11月底的一天,她又是最晚離開(kāi)公司的那一個(gè)。風(fēng)很大,北方冬...
    魚兒要飛了閱讀 374評(píng)論 5 3
  • 宜興紫砂所用的原料是:紫泥,綠泥(本山綠泥)燒成后為黃色,紅泥三種,統(tǒng)稱為紫砂泥,產(chǎn)于宜興丁蜀鎮(zhèn)黃龍山深藏于黃石巖...
    石破天聊紫砂閱讀 559評(píng)論 0 0
  • “大娘,真是免費(fèi)送給我們的?不會(huì)最后再算賬吧?” “臭小子,我啥時(shí)候騙過(guò)你呀?閉上嘴快吃你的吧,趁熱才好吃呢。” ...
    休文刀閱讀 107評(píng)論 0 1
  • 在劉若英的那首《后來(lái)》里,我清晰地看到了那個(gè)可愛(ài)并可笑的自己。后來(lái),我總算學(xué)會(huì)了如何去愛(ài),可惜你,早已遠(yuǎn)去...
    讓你猜你就猜閱讀 250評(píng)論 0 0

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