Python Return error from function

GPB picture GPB · Nov 27, 2015 · Viewed 63.6k times · Source

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?

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?

Answer

memoselyk picture memoselyk · Nov 27, 2015

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").

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. 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.