简体   繁体   中英

How to break out of parent function?

If I want to break out of a function, I can call return .

What if am in a child function and I want to break out of the parent function that called the child function? Is there a way to do this?

A minimal example:

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."

This is what exception handling is for:

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."

Then the parent function won't catch the exception and it will keep going up the stack until it finds someone who does.

If you want to rethrow the same exception you can just use 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."

Or, you can convert the Exception to something more specific by saying something like raise ASpecificException .

you can use this (works on 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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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