如何突破父功能?

时间:2016-03-10 22:33:51

标签: python

如果我想要突破某个功能,我可以致电return

如果我在子函数中并且我想要打破调用子函数的父函数,该怎么办?有没有办法做到这一点?

一个最小的例子:

def parent():
    print 'Parent does some work.'
    print 'Parent delegates to child.'
    child()
    print 'This should not execute if the child fails(Exception).' 

def child():
    try:
        print 'The child does some work but fails.'
        raise Exception
    except Exception:
        print 'Can I call something here so the parent ceases work?'
        return
    print "This won't execute if there's an exception."

2 个答案:

答案 0 :(得分:2)

这就是异常处理的目的:

def child():
    try:
        print 'The child does some work but fails.'
        raise Exception
    except Exception:
        print 'Can I call something here so the parent ceases work?'
        raise Exception  # This is called 'rethrowing' the exception
    print "This won't execute if there's an exception."

然后父函数不会捕获异常,它会继续向上移动,直到找到有人为止。

如果您想重新抛出相同的异常,可以使用raise

def child():
    try:
        print 'The child does some work but fails.'
        raise Exception
    except Exception:
        print 'Can I call something here so the parent ceases work?'
        raise  # You don't have to specify the exception again
    print "This won't execute if there's an exception."

或者,您可以通过Exception之类的内容将raise ASpecificException转换为更具体的内容。

答案 1 :(得分:1)

您可以使用它(适用于python 3.7):

def parent():
    parent.returnflag = False
    print('Parent does some work.')
    print('Parent delegates to child.')
    child()
    if parent.returnflag == True:
        return
    print('This should not execute if the child fails(Exception).')

def child():
    try:
        print ('The child does some work but fails.')
        raise Exception
    except Exception:
        parent.returnflag = True
        print ('Can I call something here so the parent ceases work?')
        return
    print ("This won't execute if there's an exception.")