Python 丟擲異常
丟擲異常
作為 Python 開發者,如果出現某個條件,您可以選擇丟擲異常。
要丟擲(或引發)異常,請使用 raise
關鍵字。
示例
Raise an error and stop the program if x is lower than 0
x = -1
if x < 0
raise Exception("Sorry, no numbers below zero")
自己動手試一試 »
The raise
keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
示例
Raise a TypeError if x is not an integer
x = "hello"
if not type(x) is int
raise TypeError("Only integers are allowed")
自己動手試一試 »