Python 从函数返回错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33962267/
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 14:15:51  来源:igfitidea点击:

Python Return error from function

pythonerror-handlingbreak

提问by GPB

I am writing a python function which uses two arrays of equal size [n,1]. Before performing any calculations, I'd like to check to ensure the lengths are the same, and if not, return an error. What is the best practice?

我正在编写一个 python 函数,它使用两个大小相等的数组 [n,1]。在执行任何计算之前,我想检查以确保长度相同,如果不相同,则返回错误。最佳做法是什么?

def do_some_stuff(array1, array2): 
# Before doing stuff, check to ensure both arrays have the same length

if len(array1) != len(array2):
#  Break and return with error

I'm confused, because I want to break and return an error code (say -1). Seems that break will return without any value, and return will continue to execute the function? Or does Return break out of any remaining code?

我很困惑,因为我想中断并返回错误代码(比如 -1)。好像break会返回没有任何值,return会继续执行函数?或者 Return 是否突破了任何剩余的代码?

采纳答案by k4ppa

You don't need the break

你不需要 break

def do_some_stuff(array1, array2): 
    # Before doing stuff, check to ensure both arrays have the same length

   if len(array1) != len(array2):
       return -1

Just return the error code. In this way the rest of the code of the function will not be executed.

只需返回错误代码。这样,函数的其余代码将不会被执行。

回答by memoselyk

What is the best practice?

最佳做法是什么?

In python code, error conditions are usually indicated with exceptions. You could use raise ValueError("Arrays must have the same size").

在python代码中,错误条件通常用异常表示。你可以使用raise ValueError("Arrays must have the same size").

Using exception rather than return values to indicate errors has the added advantage that the exception would bubble up until it reaches a exceptstatement. So you can defer the error handling up to a place where it makes sense. Also exceptions have an associated descriptive message instead of a magic number.

使用异常而不是返回值来指示错误有一个额外的好处,即异常会冒泡,直到它到达一个except语句。因此,您可以将错误处理推迟到有意义的地方。异常也有相关的描述性消息而不是幻数。

The breakstatement, as in many other languages, is used to interrupt the flow in loops, like ones created with whileor for.

与许多其他语言一样,该break语句用于中断循环中的流程,例如使用while或创建的循环for