在Python中使用 raise 关键字
Pythonraise关键字
raise是一个关键字(区分大小写),在python中,它被用来引发带有定制消息的异常/错误,并停止程序的执行。
当您要使用输入验证时,它非常有用。例如,如果您使用正数而有人输入了负数,那么在这种情况下,我们可能会引发错误并停止程序的执行。
raise关键字的语法
if test_condition: raise Exception(Message)
示例
Input: string = "Hello" if string=="Hello" or string=="Hi" or string=="Bye": raise Exception("This word is not allowed") Output: Exception: This word is not allowed
raise关键字的Python示例
示例1:输入一个正数,如果输入为负数,则引发异常。
# python代码演示示例 # 提高关键字 # 输入一个正数并引发异常 # 如果输入为负值 num = int(input("Enter a positive number: ")) if num<0: raise Exception("Please input only positive value ") print("num = ", num)
输出结果
First run: Enter a positive number: 20 num = 20 Second run: Enter a positive number: -10 Traceback (most recent call last): File "/home/main.py", line 10, in <module> raise Exception("Please input only positive value ") Exception: Please input only positive value
示例2:输入字符串,并在特定单词上引发异常。
# python代码演示示例 # 提高关键字 # 输入字符串并在特定单词上引发异常 string = input("Input a string: ") # 文字-我们正在检查 # “你好”,“嗨”或“再见” if string=="Hello" or string=="Hi" or string=="Bye": raise Exception("This word is not allowed") print("The input was: ", string)
输出结果
First run: Input a string: nhooo The input was: nhooo Second run: Input a string: Hello Traceback (most recent call last): File "/home/main.py", line 11, in <module> raise Exception("This word is not allowed") Exception: This word is not allowed Third run: Input a string: Bye Traceback (most recent call last): File "/home/main.py", line 11, in <module> raise Exception("This word is not allowed") Exception: This word is not allowed