異常的原因通常在程序本身之外。例如,不正確的輸入、輸入輸出設備故障等。由于程序在遇到異常時會突然終止,因此可能會對系統資源(如文件)造成損害。因此,應該正確處理異常,以防止程序突然終止。
Python 使用try
和except
關鍵字來處理異常。兩個關鍵字后面都有縮進塊。
Syntax:
try :
#statements in try block
except :
#executed when error in try block
try:塊包含一個或多個可能會遇到異常的語句。如果此塊中的語句無異常執行,則跳過后續的 except:塊。
如果異常確實發生,程序流將轉移到 except:塊。except:
塊中的語句旨在適當地處理異常的原因。 例如,返回適當的錯誤消息。
您可以在except
關鍵字后指定異常的類型。只有當指定的異常發生時,才會執行后續塊。 一個 try 塊中可能有多個異常類型不同的 except 子句。如果異常類型與任何異常塊都不匹配,它將保持未處理狀態,程序將終止。
除塊之后的其余語句將繼續執行,不管是否遇到異常。
下面的示例將在我們試圖用字符串來設計整數時引發異常。
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 關鍵字前面提到特定類型的異常。只有當指定的異常發生時,才會執行后續塊。在一個 try 塊中可能有多個具有不同異常類型的 except 子句。如果異常類型與任何異常塊都不匹配,它將保持未處理狀態,程序將終止。
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 子句一起使用。 如果異常發生在 try 塊內部,則執行 except 塊,如果發現 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 塊中是否出現異常,這些語句都應該被處理。因此,無錯誤的 try 塊會跳過 except 子句,并在繼續執行其余代碼之前進入 finally 塊。但是,如果 try 塊中有異常,將處理適當的 except 塊,并且在繼續執行代碼的其余部分之前,將處理 finally 塊中的語句。
下面的示例接受來自用戶的兩個數字并執行它們的除法。它演示了 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.
第二次運行是被零除的情況,因此,執行 except 塊和 finally 塊,但不執行 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.
在第三次運行的情況下,出現了一個未捕獲的異常。final 塊仍然被執行,但是程序終止,并且在 final 塊之后不執行程序。
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 <module>
y=int(input('Enter another number: '))
ValueError: invalid literal for int() with base 10: 'xyz'
通常,finally 子句是清理流程中操作的理想位置。例如,不管讀/寫操作中的錯誤如何,都要關閉文件。這將在下一章討論。
引發異常
Python 還提供了raise
關鍵字,用于異常處理的上下文中。它導致顯式生成異常。隱式引發內置錯誤。但是,可以在執行過程中強制執行內置或自定義異常。
下面的代碼接受來自用戶的數字。如果數值超出允許的范圍,try 塊將引發 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
這里,引發的異常是ValueError
類型。但是,您可以定義要引發的自定義異常類型。 訪問 Python 文檔,了解更多關于用戶定義異常的信息。*****