2016-03-10 41 views
2

如果我想突破某個功能,我可以撥打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." 
+5

引發異常並讓父函數捕獲它。你不能沒有家長的監督; – zondo

回答

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更具體的東西。

+3

或只是一個裸'提高',如果你想在原處理後重新提出一些處理 – wim

+0

好點。我會詳細說明。 –

+0

至少提供前一個例外的上下文。否則,如果有什麼不好的事情發生,結果堆棧跟蹤可能會令人困惑。 – tommus