如何退出Python函数,在不退出Python interp的情况下抛出错误语句

2024-03-28 12:09:19 发布

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

我是Python新手,在处理自定义错误方面很吃力。当我的代码发现错误时,我希望它以红色字体抛出一个错误,并将我带回Python终端,而不杀死Python。

我遇到sys.exit()正在寻找答案,但它完全退出了Python。你知不知道还有一种方法可以用红色字体返回一个错误,然后把我带回终端?

这就是我目前所拥有的。

import sys
def do_something(parameter):
    if parameter > 100:
        # quit the function and any function(s) that may have called it
        sys.exit('Your parameter should not be greater than 100!')
    else:
        # otherwise, carry on with the rest of the code

如果我不清楚,请告诉我,我很乐意提供更多细节。提前谢谢大家!


Tags: the方法答案代码import终端parameter错误
2条回答

定义自定义异常并引发它。

class MyError(Exception):
    pass

...

if parameter > 100:
    # quit the function and any function(s) that may have called it
    raise MyError('Your parameter should not be greater than 100!')

(尽管实际上,现在我考虑了一下,您可以使用一个内置的异常:ValueError似乎是合适的)。

你至少有两个选择。

使用return语句:

def do_something(parameter):
    if parameter > 100:
        # display error message if necessary
        return  # 'exit' function and return to caller
    # rest of the code

您还可以return soemthingsomething值传递回调用方。这可用于提供状态代码(例如0:成功,1:错误)。

或者更好的方法是raise例外:

def do_something(parameter):
    if parameter > 100:
        raise ValueError('Parameter should...')
    # rest of the code

try:
    do_something(101)
except ValueError, e:
    # display error message if necessary e.g. print str(e)

请参见Python手册中的exceptions

有内置的异常类(如上面的ValueError)。您也可以定义如下:

class ParameterError(Exception):
    pass

您还可以向自定义异常类添加其他代码以处理参数、显示自定义错误消息等。。。

列出了内置异常here

相关问题 更多 >