Skip to content

Instantly share code, notes, and snippets.

@dannyroberts
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannyroberts/9747745 to your computer and use it in GitHub Desktop.
Save dannyroberts/9747745 to your computer and use it in GitHub Desktop.

Error handling antipattern

So I trace down a 500 to the line:

foo.get_bar(bar)

which is raising an IndexError. I figure out it means that there is no such bar, and that in that case we want to do nothing, so I change it to

BAD

try:
    foo.get_bar(bar)
except IndexError:
    return

Why's that bad? Well, it makes for a very strange API. How's it obvious at all

  1. that get_bar can raise an IndexError and
  2. that when it does it signifies that it looked up that there's no such bar?

Instead, you should either raise a custom exception for that purpose (and document it in the method) or in this particular case perhaps return None.

GOOD

Inside get_bar:

...
try:
    myarray[bar.id]
except IndexError:
    raise NoSuchBar(bar.id)
...

Inside the module's exceptions.py:

class NoSuchBar(Exception):
    pass

Original line:

try:
    foo.get_bar(bar)
except NoSuchBar:
    return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment