Python except關鍵字



Python 的except關鍵字用於異常處理。如果程式中出現錯誤,程式碼的其餘部分將不會執行。為了處理錯誤並瞭解錯誤的型別,我們使用except塊。只有當try塊中引發錯誤時,才會執行此塊。

如果程式碼中在沒有try塊的情況下使用except塊,它將引發SyntaxError。在程式中,為了瞭解發生的錯誤型別,我們在except塊中使用exception。這是一個區分大小寫的關鍵字,它建立except塊。

語法

以下是Pythonexcept關鍵字的語法:

try:
    statement1
except:
    statement2

示例

以下是Pythonexcept關鍵字的基本示例:

try :
    print("Welcome to the Tutorialspoint")
except:
    print("Error")

輸出

以下是上述程式碼的輸出:

Welcome to the Tutorialspoint

except塊中的錯誤型別

當我們在except塊中使用Exception時,我們可以瞭解try塊中引發的錯誤型別。

示例

這裡,我們在try塊中給出了一個關鍵語句,該語句會引發錯誤。我們在except塊中找到了錯誤的型別:

var1 = 1
var2 = 0
try :
    print(var1//var2)
except Exception as e:
    print("Type of Error :",e)

輸出

以下是上述程式碼的輸出:

Type of Error : integer division or modulo by zero

將'except'與finally一起使用

無論try塊是否引發錯誤,都會執行finally塊。

示例

以下是包含finally的except塊的示例:

var1 = 9
var2 = 'zero'
try :
    print(var1//var2)
except Exception as e:
    print("Error :",e)
finally:
    print("This block is executed irrespective to the error") 

輸出

以下是上述程式碼的輸出:

Error : unsupported operand type(s) for //: 'int' and 'str'
This block is executed irrespective to the error
python_keywords.htm
廣告
© . All rights reserved.