Skip to content Skip to sidebar Skip to footer

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

Solution 1:

This is what exception handling is for:

defchild():
    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 exceptionprint"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:

defchild():
    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 againprint"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.

Solution 2:

you can use this (works on python 3.7):

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

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

Post a Comment for "How To Break Out Of Parent Function?"