如何退出Python函数,抛出错误语句而不退出Python解释器

Gya*_*eda 15 python error-handling exception function quit

我是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
Run Code Online (Sandbox Code Playgroud)

如果我不清楚,请告诉我,我很乐意提供更多详情.谢谢大家!

ise*_*dev 24

你有两个选择(至少).

使用return声明:

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

您还可以return soemthing将something值传递回调用者.这可用于提供例如状态代码(例如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)
Run Code Online (Sandbox Code Playgroud)

请参阅Python手册中的例外.

有内置的异常类(ValueError如上所述).您也可以按如下方式定义自己的:

class ParameterError(Exception):
    pass
Run Code Online (Sandbox Code Playgroud)

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

此处列出了内置异常.