Python raise 關鍵字

實例

如果 x 小于 0,則引發錯誤并停止程序:

x = -1
if x < 0:
  raise Exception("Sorry, no numbers below zero")

運行實例

定義和用法

raise 關鍵字用于引發異常。

您可以定義要引發的錯誤類型以及要向用戶打印的文本。

更多實例

實例

如果 x 不是整數,則引發 TypeError:

x = "hello"
if not type(x) is int:
  raise TypeError("Only integers are allowed")

運行實例