简体   繁体   English

如何使用try和except在python中捕获函数失败

[英]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. 我在看文档,尝试try以及那里列出的内置值,但是我弄清楚了应该使用什么来捕获一般功能失败。 here's what I mean say I have these: foo.py 我的意思是说我有这些: 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: 使用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. 和BananaMaker.py分别看起来与appleMaker.py完全相同。 What I want to be able to do is in foo, something like: 我想要做的是在foo中,例如:

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

Generally you would read the documentation for create_apple() to see what exceptions it can raise, and catch those. 通常,您会阅读有关create_apple()的文档,以查看它会引发哪些异常并捕获这些异常。

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. 但是,与Java不同,Python函数不需要声明它们可以引发的所有可能的异常,因此可以想象任何函数都可以引发许多不同的异常。

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. 两种方式都可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM