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
- that
get_bar
can raise anIndexError
and - 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