Python except 關鍵字

實例

如果語句引發錯誤,則打印 "Something went wrong":

try:
  x > 3
except:
  print("Something went wrong")

運行實例

定義和用法

在 try ... except 塊中使用了關鍵字 except。它定義 try 塊引發錯誤時要運行的代碼塊。

您可以為不同的錯誤類型定義不同的塊,以及沒有問題的情況下執行的塊,請參見下面的例子。

更多實例

實例 1

如果引發 NameError 則寫一條消息,如果引發 TypeError 則寫另一條:

x = "hello"
try:
  x > 3
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")

運行實例

實例 2

嘗試執行一條引發錯誤的語句,但沒有定義的錯誤類型(在這種情況下為 ZeroDivisionError):

try:
  x = 1/0
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")
except:
  print("Something else went wrong")

運行實例

實例 3

如果沒有出現錯誤,寫一條消息:

x = 1
try:
  x > 10
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")
else:
  print("The 'Try' code was executed without raising any errors!")

運行實例

相關頁面

try 關鍵字

finally 關鍵字