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í)行流程:
- 如果try后的語(yǔ)句運(yùn)行無(wú)誤,那么python繼續(xù)執(zhí)行 try-except 后面的語(yǔ)句;
- 如果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í)行流程:
- 如果try后的語(yǔ)句運(yùn)行無(wú)誤,那么python先運(yùn)行else后的語(yǔ)句,再執(zhí)行 try-except-else 后面的語(yǔ)句;
- 如果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