Where to post exception handling in python

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

For example, which of the following options is preferable?

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 calm on this matter, and I seem to find examples of both cases everywhere.

+6
source share
3 answers

It really depends on the semantics of the functions in question. In general, if you are writing a library, your library should probably handle the exceptions that occur in the library (possibly recreating them as new exceptions for the library).

However, at the level of individual functions, the main thing you want to think about is what context / area in which you want to handle the exception - if there is a reasonable difference that you could make in exceptional cases inside an internal function, it would be useful to handle it inside an internal function; otherwise, it may make sense to handle it in an external function.

For a particular case of writing output, it is often useful to do this only at the highest level, and internal functions only ever (a) return values ​​or (b) throw exceptions. This simplifies code verification because you don’t have to worry about testing a side effect.

+6
source

If you follow the rule "one function should handle one task", then you should not handle the exception in this function, let it fail when unexpected input. A parent function that invokes such a function can cope with giving the user a better experience.

We can reference python built-in functions to get the Python path

+2
source

I always use the second one. Logically, it seems to me that the problems of a function should be solved only in this function. This will provide the user with a clean and convenient interface, so later you can put your code in the library.

There may be times when you want to use exceptions outside the function. For example, if you want to print a specific message when something goes wrong, you should use an exception from the function.

However, you could provide exception instructions as an argument to the function if you want to give the user the opportunity to decide their own exception message. Therefore, I suggest that the second example (an exception inside a function) will be universal and therefore should be preferred.

0
source

All Articles