Search code examples
pythoncoding-style

Python - Clean Code, no implemented exceptions?


I am working on an API that allows simple data manipulation for a certain schema of python dicts. The user can pass parameters that are used as keys in those dicts. For example:

def get_columns(self, name):
    for ... in self.data[name]:
       ...
    ...

If name is not in the data dict it should throw an exception.

My question is: Do I need to add such exception handling? The dict would raise a KeyError itself. What is better practice?


Solution

  • If you want the function to simply throw a KeyError and nothing else, there's no need to wrap it in a try except statement (it would be redundant since the exception would propagate up the call stack anyways).

    If you want it to have some other behaviour (for example, skip the for loop, return a specialized error message, maybe return a default value of some kind), that's when you would want to use exception handling.