25

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?

GPB
  • 2,395
  • 8
  • 26
  • 36
  • 1
    Possible duplicate of [Manually raising (throwing) an exception in Python](http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python). That question handles how to manually raise an error, which prevents the script from continuing after returning from a function. – SuperBiasedMan Nov 27 '15 at 17:26
  • 1
    `return` will not continue to execute the function – katy lavallee Nov 27 '15 at 17:28

2 Answers2

73

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.

memoselyk
  • 3,993
  • 1
  • 17
  • 28
4

You don't need the 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.

k4ppa
  • 4,122
  • 8
  • 26
  • 36