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

專注于為中小企業(yè)提供成都做網(wǎng)站、成都網(wǎng)站建設服務,電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)分宜免費做網(wǎng)站提供優(yōu)質的服務。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了數(shù)千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設實現(xiàn)規(guī)模擴充和轉變。
Python 使用try和except關鍵字來處理異常。兩個關鍵字后面都有縮進塊。
Syntax:
try :
#statements in try block
except :
#executed when error in try block
try:塊包含一個或多個可能會遇到異常的語句。如果此塊中的語句無異常執(zhí)行,則跳過后續(xù)的 except:塊。
如果異常確實發(fā)生,程序流將轉移到 except:塊。except:塊中的語句旨在適當?shù)靥幚懋惓5脑颉?例如,返回適當?shù)腻e誤消息。
您可以在except關鍵字后指定異常的類型。只有當指定的異常發(fā)生時,才會執(zhí)行后續(xù)塊。 一個 try 塊中可能有多個異常類型不同的 except 子句。如果異常類型與任何異常塊都不匹配,它將保持未處理狀態(tài),程序將終止。
除塊之后的其余語句將繼續(xù)執(zhí)行,不管是否遇到異常。
下面的示例將在我們試圖用字符串來設計整數(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 關鍵字前面提到特定類型的異常。只有當指定的異常發(fā)生時,才會執(zhí)行后續(xù)塊。在一個 try 塊中可能有多個具有不同異常類型的 except 子句。如果異常類型與任何異常塊都不匹配,它將保持未處理狀態(tài),程序將終止。
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
如上所述,單個嘗試塊可以有多個例外塊。以下示例使用兩個 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 設置為“0”,將會遇到類型錯誤,并由相應的異常塊處理。
否則最后
在 Python 中,關鍵字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)異常,這些語句都應該被處理。因此,無錯誤的 try 塊會跳過 except 子句,并在繼續(xù)執(zhí)行其余代碼之前進入 finally 塊。但是,如果 try 塊中有異常,將處理適當?shù)?except 塊,并且在繼續(xù)執(zhí)行代碼的其余部分之前,將處理 finally 塊中的語句。
下面的示例接受來自用戶的兩個數(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 塊,因為 try 塊是無錯誤的。
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.
第二次運行是被零除的情況,因此,執(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.
在第三次運行的情況下,出現(xiàn)了一個未捕獲的異常。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 子句是清理流程中操作的理想位置。例如,不管讀/寫操作中的錯誤如何,都要關閉文件。這將在下一章討論。
引發(fā)異常
Python 還提供了raise關鍵字,用于異常處理的上下文中。它導致顯式生成異常。隱式引發(fā)內(nèi)置錯誤。但是,可以在執(zhí)行過程中強制執(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 文檔,了解更多關于用戶定義異常的信息。*****
網(wǎng)站欄目:Python中的異常處理
網(wǎng)站地址:http://m.fisionsoft.com.cn/article/coecspp.html


咨詢
建站咨詢
