如何跳出父函数?

chi*_*aku 5 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."
Run Code Online (Sandbox Code Playgroud)

Nat*_*ord 3

这就是异常处理的目的:

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."
Run Code Online (Sandbox Code Playgroud)

那么父函数将不会捕获异常,并且它将继续在堆栈中向上查找,直到找到捕获异常的人。

如果你想重新抛出相同的异常,你可以使用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."
Run Code Online (Sandbox Code Playgroud)

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

  • 或者只是一个简单的“raise”,如果你想在一些处理后重新引发原始异常 (3认同)
  • @tommus:在Python 3中,该上下文是自动的,除非您覆盖异常上下文链接(通过将“from None”添加到新“raise”语句的末尾)。在 Py2 中,是的,你必须遇到一些麻烦。 (3认同)