Jared Sanchez Jared Sanchez - 1 year ago 159
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:

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

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):

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:

except Exception:
print "informative information"

Answer Source

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:


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)


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download