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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22132272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:19:18  来源:igfitidea点击:

How to quit Python function, throwing error statement without quitting Python interpreter

pythonfunctionexceptionerror-handlingquit

提问by Gyan Veda

I'm new to Python and struggling with handling self-defined errors. When my code spots the error, I want it to throw an error in red font and take me back to the Python terminal without killing Python.

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

I came across sys.exit() looking for an answer, but it quits Python completely. Do you know of an alternative that throws back an error in red font andtakes me back to the terminal?

我遇到了 sys.exit() 寻找答案,但它完全退出了 Python。你知道吗,回抛出以红色字体出现错误的替代,并把我带回到终端?

This is what I have so far.

这是我到目前为止。

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

Please let me know if I'm not clear and I'll be happy to provide more details. Thank you all in advance!

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

采纳答案by isedev

You have two options (at least).

你有两个选择(至少)。

Using a returnstatement:

使用return语句:

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

You can also return soemthingpassing the somethingvalue back to the caller. This can be used to provide a status code for instance (e.g. 0: success, 1: error).

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

Or a better approach is to raisean exception:

或者更好的方法是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)

See exceptionsin the Python manual.

请参阅Python 手册中的异常

There are built-in exception classes (like ValueErrorabove). You can also define your own as follows:

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

class ParameterError(Exception):
    pass

You can also add additional code to your custom exception classes to process parameters, display custom error messages, etc...

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

The built-in exceptions are listed here.

此处列出内置异常。

回答by Daniel Roseman

Define a custom exception, and raise it.

定义一个自定义异常,并引发它。

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!')

(although actually, now I think about it, you could just use a built-in exception: ValueError would seem appropriate).

(尽管实际上,现在我想一想,您可以只使用内置异常:ValueError 似乎合适)。