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

smith picture smith · Jul 14, 2014 · Viewed 10.1k times · Source

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?

Answer

Jan Vlcinsky picture Jan Vlcinsky · Jul 14, 2014

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.