rh1990
rh1990

Reputation: 940

Python 'try - except - else' handling multiple possible outcomes simultaneously

I have a function that fits to a 1D array of data, but this function can fail if the data is inappropriate and will raise a RuntimeError.

As my data is a 2D array I want to try it on both axis of the data if possible, otherwise just run it on the one axis that doesn't throw the error.

If I've understood the notation correctly, I try myfunc on my data in the 1st axis, if this fails go to the second, otherwise go back to the 1st. E.g. for the 1st column or row:

def myfunc(data):
    # some code to do a fit, might crash
    return fit_params

data = np.random.random((5,5))

try:
    results_y = myfunc(data[0,:])

except RuntimeError:
    results_x = myfunc(data[:,0])
    # some math on the results

else:
    results_y = myfunc(data[0,:])
    # some math on the results

However, in some scenarios, it would work on both with no error, and it would be useful to see/compare both the results. How do I write this loop such that it will execute both if possible, otherwise will just do the one that worked? I'm thinking of either putting it all in an if loop or having multiple try statements?

Thanks in advance

Upvotes: 0

Views: 151

Answers (1)

blue note
blue note

Reputation: 29099

Just two independent try..except clauses

try:
    results_y = myfunc(data[0,:])
except RuntimeError:
    pass

try:
    results_x = myfunc(data[:,0])
except RuntimeError:
    pass

However, there's no need to do that. It all depends on the number of dimensions of your array, so it would be probably be better to check my_array.ndim or my_array.shape to decide what to do.

Upvotes: 2

Related Questions