简体   繁体   English

Python函数返回错误

[英]Python Return error from function

I am writing a python function which uses two arrays of equal size [n,1]. 我正在编写一个python函数,它使用两个大小相等的数组[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? 什么是最佳做法?

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). 我很困惑,因为我想打破并返回错误代码(比如-1)。 Seems that break will return without any value, and return will continue to execute the function? 似乎break将返回没有任何值,返回将继续执行该函数? Or does Return break out of any remaining code? 或者Return是否会突破任何剩余的代码?

What is the best practice? 什么是最佳做法?

In python code, error conditions are usually indicated with exceptions. 在python代码中,错误条件通常用异常表示。 You could use raise ValueError("Arrays must have the same size") . 您可以使用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 except statement. 使用异常而不是返回值来指示错误具有额外的优势,即异常会在到达except语句之前冒泡。 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. 异常也有相关的描述性消息而不是幻数。

The break statement , as in many other languages, is used to interrupt the flow in loops, like ones created with while or for . 与许多其他语言一样, break语句用于中断循环中的流,例如使用whilefor创建的循环。

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. 这样,函数的其余代码将不会被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM