Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to use a return statement within a try and except statement?

If I have such code in the end of function:

try:
    return map(float, result)
except ValueError, e:
    print "error", e

Is it correct to use try / except in return part of method? Is there a wiser way to solve this?

like image 824
smith Avatar asked Jul 14 '14 07:07

smith


1 Answers

Keep it simple: no try block

It took me a while to learn, that in Python it is natural, that functions throw exceptions up. I have spent too much effort on handling these problems in the place the problem occurred.

The code can become much simpler and also easier to maintain if you simply let the exception bubble up. This allows for detecting problems on the level, where it is appropriate.

One option is:

try:
    return map(float, result)
except ValueError, e:
    print "error", e
    raise

but this introduces print from within some deep function. The same can be provided by raise which let upper level code to do what is appropriate.

With this context, my preferred solution looks:

return map(float, result)

No need to dance around, do, what is expected to be done, and throw an exception up, if there is a problem.

like image 160
Jan Vlcinsky Avatar answered Oct 17 '22 02:10

Jan Vlcinsky