Python Try Except
The try
block lets you test a block of code for errors.
The except
block lets you handle the error.
The finally
block lets you execute code, regardless of the result of the try- and except blocks.
多種異常
您可以定義任意數量的異常塊,例如,如果您想為特定型別的錯誤執行特殊的程式碼塊
示例
如果 try 塊引發 NameError
,則列印一條訊息;如果引發其他錯誤,則列印另一條訊息
try
print(x)
except NameError
print("變數 x 未定義")
except
print("Something else went wrong")
自己動手試一試 »