新聞中心
異常的原因通常在程序本身之外。例如,不正確的輸入、輸入輸出設(shè)備故障等。由于程序在遇到異常時(shí)會(huì)突然終止,因此可能會(huì)對(duì)系統(tǒng)資源(如文件)造成損害。因此,應(yīng)該正確處理異常,以防止程序突然終止。

專注于為中小企業(yè)提供成都做網(wǎng)站、成都網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)分宜免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了數(shù)千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
Python 使用try和except關(guān)鍵字來處理異常。兩個(gè)關(guān)鍵字后面都有縮進(jìn)塊。
Syntax:
try :
#statements in try block
except :
#executed when error in try block
try:塊包含一個(gè)或多個(gè)可能會(huì)遇到異常的語句。如果此塊中的語句無異常執(zhí)行,則跳過后續(xù)的 except:塊。
如果異常確實(shí)發(fā)生,程序流將轉(zhuǎn)移到 except:塊。except:塊中的語句旨在適當(dāng)?shù)靥幚懋惓5脑颉?例如,返回適當(dāng)?shù)腻e(cuò)誤消息。
您可以在except關(guān)鍵字后指定異常的類型。只有當(dāng)指定的異常發(fā)生時(shí),才會(huì)執(zhí)行后續(xù)塊。 一個(gè) try 塊中可能有多個(gè)異常類型不同的 except 子句。如果異常類型與任何異常塊都不匹配,它將保持未處理狀態(tài),程序?qū)⒔K止。
除塊之后的其余語句將繼續(xù)執(zhí)行,不管是否遇到異常。
下面的示例將在我們?cè)噲D用字符串來設(shè)計(jì)整數(shù)時(shí)引發(fā)異常。
Example: try...except blocks
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")
Output
Some error occurred.
Out of try except blocks.
您可以在 except 關(guān)鍵字前面提到特定類型的異常。只有當(dāng)指定的異常發(fā)生時(shí),才會(huì)執(zhí)行后續(xù)塊。在一個(gè) try 塊中可能有多個(gè)具有不同異常類型的 except 子句。如果異常類型與任何異常塊都不匹配,它將保持未處理狀態(tài),程序?qū)⒔K止。
Example: Catch Specific Error Type
try:
a=5
b='0'
print (a+b)
except TypeError:
print('Unsupported operation')
print ("Out of try except blocks")
Output
Unsupported operation
Out of try except blocks
如上所述,單個(gè)嘗試塊可以有多個(gè)例外塊。以下示例使用兩個(gè) except 塊來處理兩種不同的異常類型:
Example: Multiple except Blocks
try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
print ('Out of try except blocks')
Output
Division by zero not allowed
Out of try except blocks
但是,如果變量 b 設(shè)置為“0”,將會(huì)遇到類型錯(cuò)誤,并由相應(yīng)的異常塊處理。
否則最后
在 Python 中,關(guān)鍵字else和finally也可以與 try 和 except 子句一起使用。 如果異常發(fā)生在 try 塊內(nèi)部,則執(zhí)行 except 塊,如果發(fā)現(xiàn) try 塊沒有異常,則處理 else 塊。
Syntax:
try:
#statements in try block
except:
#executed when error in try block
else:
#executed if try block is error-free
finally:
#executed irrespective of exception occured or not
finally 塊由語句組成,無論 try 塊中是否出現(xiàn)異常,這些語句都應(yīng)該被處理。因此,無錯(cuò)誤的 try 塊會(huì)跳過 except 子句,并在繼續(xù)執(zhí)行其余代碼之前進(jìn)入 finally 塊。但是,如果 try 塊中有異常,將處理適當(dāng)?shù)?except 塊,并且在繼續(xù)執(zhí)行代碼的其余部分之前,將處理 finally 塊中的語句。
下面的示例接受來自用戶的兩個(gè)數(shù)字并執(zhí)行它們的除法。它演示了 else 和 finally 塊的用法。
Example: try, except, else, finally blocks
try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
第一次跑步是正常情況。顯示 out of else 和 finally 塊,因?yàn)?try 塊是無錯(cuò)誤的。
Output
try block
Enter a number: 10
Enter another number: 2
else block
Division = 5.0
finally block
Out of try, except, else and finally blocks.
第二次運(yùn)行是被零除的情況,因此,執(zhí)行 except 塊和 finally 塊,但不執(zhí)行 else 塊。
Output
try block
Enter a number: 10
Enter another number: 0
except ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.
在第三次運(yùn)行的情況下,出現(xiàn)了一個(gè)未捕獲的異常。final 塊仍然被執(zhí)行,但是程序終止,并且在 final 塊之后不執(zhí)行程序。
Output
try block
Enter a number: 10
Enter another number: xyz
finally block
Traceback (most recent call last):
File "C:\python36\codes\test.py", line 3, in
y=int(input('Enter another number: '))
ValueError: invalid literal for int() with base 10: 'xyz'
通常,finally 子句是清理流程中操作的理想位置。例如,不管讀/寫操作中的錯(cuò)誤如何,都要關(guān)閉文件。這將在下一章討論。
引發(fā)異常
Python 還提供了raise關(guān)鍵字,用于異常處理的上下文中。它導(dǎo)致顯式生成異常。隱式引發(fā)內(nèi)置錯(cuò)誤。但是,可以在執(zhí)行過程中強(qiáng)制執(zhí)行內(nèi)置或自定義異常。
下面的代碼接受來自用戶的數(shù)字。如果數(shù)值超出允許的范圍,try 塊將引發(fā) ValueError 異常。
Example: Raise an Exception
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
Output
Enter a number upto 100: 200
200 is out of allowed range
Enter a number upto 100: 50
50 is within the allowed range
這里,引發(fā)的異常是ValueError類型。但是,您可以定義要引發(fā)的自定義異常類型。 訪問 Python 文檔,了解更多關(guān)于用戶定義異常的信息。*****
網(wǎng)站欄目:Python中的異常處理
URL地址:http://m.5511xx.com/article/coecspp.html


咨詢
建站咨詢
