When is exception handling more preferable than condition checking? There are many situations where I can choose using one or the other.
For example, this is a summing function which uses a custom exception:
# module mylibrary
class WrongSummand(Exception):
pass
def sum_(a, b):
""" returns the sum of two summands of the same type """
if type(a) != type(b):
raise WrongSummand("given arguments are not of the same type")
return a + b
# module application using mylibrary
from mylibrary import sum_, WrongSummand
try:
print sum_("A", 5)
except WrongSummand:
print "wrong arguments"
And this is the same function, which avoids using exceptions
# module mylibrary
def sum_(a, b):
""" returns the sum of two summands if they are both of the same type """
if type(a) == type(b):
return a + b
# module application using mylibrary
from mylibrary import sum_
c = sum_("A", 5)
if c is not None:
print c
else:
print "wrong arguments"
I think that using conditions is always more readable and manageable. Or am I wrong? What are the proper cases for defining APIs which raise exceptions and why?
Exceptions are much more manageable, because they define general families of things that can go wrong.
In your example there is only one possible problem, so there is no advantage to using exceptions. But if you had another class that does division, then it needs to signal that you can’t devide by zero. Simply returning
Nonewouldn’t work anymore.On the other hand, exceptions can be subclassed and you can catch specific exceptions, depending on how much you care about the underlying problem. For example, you could have a
DoesntComputebase exception and subclasses likeInvalidTypeandInvalidArgument. If you just want a result, you can wrap all computations in a block that catchesDoesntCompute, but you can still do very specific error handling just as easy.