Jared Sanchez Jared Sanchez - 1 month ago 8
Python Question

How to catch function fails in python with try and except

I was looking at the documentation for try except and the built in values listed there, but I figure out what I should be using to catch a general function fail. here's what I mean say I have these:
foo.py

def create_apples(x,y,z):
appleMaker = appleMaker()
appleMaker.maker(x,y,z)
def create_bananas(x,y,z):
bananaMaker = BananaMaker()
bananaMaker.maker(x,y,z)

if __name__ == '__main__':

x = 1
y = 2
z = 3
create_apples(x, y, z)
create_bananas(x, y, z)


with appleMaker.py:

from random import randint

class appleMaker:
def __init__(self):
self.bushelID
self.numberCreated

def maker(x, y, z):
self.bushelID = randint(0,9)
self.numberCreated = x + y + z


and BananaMaker.py looking exactly the same as appleMaker.py respectively. What I want to be able to do is in foo, something like:

try:
create_apple(x,y,z)
except Exception:
print "informative information"
sys.exit(1)

Answer

Generally you would read the documentation for create_apple() to see what exceptions it can raise, and catch those.

Unlike Java, though, Python functions aren't required to declare all the possible exceptions they can raise, so any function could conceivably raise many different exceptions.

Your best bet might be some sort of catchall condition at the end:

try:
    create_apple(x,y,z)

except NoTreeFound:
    print 'could not find an apple tree'

except BasketFull:
    print 'apple basket is already full of apples'

except Winter:
    print 'Cannot create apples in winter!'

except Exception as e:
    print 'an unknown error occurred, message is: %s' % str(e)

UPDATE

It appears you're looking for advice on how a function should raise exceptions, not how a caller should catch them.

If your function can fail in several distinct ways, then defining specific exceptions for each failure condition can be convenient for the caller, as it can easily handle each failure condition separately (as I showed in the example above.)

But if your function can really only fail in one way, with possibly slightly different details in some cases, then perhaps the best thing to do is raise a general exception with a specific message:

raise Exception("my coffee is too cold")

In the end it's a design decision. Both ways will work.