Condition checking vs. Exception handling

Posted by Aidas Bendoraitis on Stack Overflow See other posts from Stack Overflow or by Aidas Bendoraitis
Published on 2010-04-29T17:53:19Z Indexed on 2010/04/29 18:57 UTC
Read the original article Hit count: 287

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about condition