在函数中停止程序(python)

2024-04-27 11:20:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点新的编码,我希望能够停止程序,如果可能抛出一个自定义的错误消息从一个函数

(如:

def Rounded_square(lots of inputs):
    radius = (calculation)
    if radius < 0:
        stop.program("The radius is negative")

()


Tags: of函数程序消息编码ifdef错误
3条回答

你想引发一个异常

raise ValueError("radius should be positive")

import osos.exit("The radius is negative")exit()函数中的值将被打印到stderr,返回代码将是1(感谢@peter wood的启示) 在此之前,您可以使用print作为消息

要抛出自定义错误消息,可以执行以下操作

raise BaseException("my exception text")

您可以查看内置异常类型here

或者,要退出程序,只需调用

exit()

相关问题 更多 >