Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put exception handling in python

When using try/except blocks in Python, is there a recommendation to delegate it to any methods that might raise an exception, or to catch it in the parent function, or both?

For example, which of the following is preferred?

def my_function():
    s = something.that.might.go_wrong()
    return s

def main():
    try:
        s = my_function()
    except Exception:
        print "Error"

or

def my_function():
    try:
        s = something.that.might.go_wrong()
        return s
    except Exception:
        print "Error"

def main():
    s = my_function()

PEP 8 seems to be quiet on the matter, and I seem to find examples of both cases everywhere.

like image 892
mcy Avatar asked Feb 05 '16 03:02

mcy


2 Answers

It really depends on the semantics of the functions in question. In general if you're writing a library, your library probably should handle exceptions that get raised inside the library (optionally re-raising them as new library-specific exceptions).

At the individual function level, though, the main thing you want to think about is what context/scope you desire to handle the exception in - if there is a reasonable different thing you could do in exceptional cases within the inner function, it might be useful to handle it within the inner function; otherwise, it might make more sense to handle it in the outer function.

For the specific case of writing output, it's often useful to only do that at the highest level, and inner functions only ever (a) return values or (b) raise exceptions. That makes the code easier to test because you don't have to worry about testing side effect output.

like image 96
Amber Avatar answered Oct 17 '22 05:10

Amber


If you are following the rule of "one function should handle one task" then You shouldn't handle exception in that function, Let it fail loudly on unexpected input. Parent function which calling such function may handle to give better experience to user.

We can refer python builtin functions to get pythonic way

like image 3
AlokThakur Avatar answered Oct 17 '22 05:10

AlokThakur