2014-01-07 60 views
0

如果執行一個異常,是否有辦法阻止try塊的其餘部分執行?比如說我用完了ingredient 1,那麼一旦執行那個異常,我怎麼才能防止try塊的其餘部分執行?如果執行一個異常,是否有辦法阻止try塊的執行?

try: 
    #add ingredient 1 
    #add ingredient 2 
    #add ingredient 3 
except MissingIngredient: 
    print 'you are missing ingredients' 
+3

你不需要做任何事情。如果在「添加成分1」中拋出異常,則其他兩個不會被執行 – Liteye

回答

4

它會自動發生:

class MissingIngredient(Exception): 
    pass 

def add_ingredient(name): 
    print 'add_ingredient',name 
    raise MissingIngredient 

try: 
    add_ingredient(1) 
    add_ingredient(2) 
    add_ingredient(3) 
except MissingIngredient: 
    print 'you are missing ingredients' 

try塊的其餘部分將不會被執行如果其中一個表達引發異常。它將打印:

add_ingredient 1 
you are missing ingredients 
0

在原始try塊中使用另一個try/catch塊。

try: 
    #add ingredient 1 
    #add ingredient 2 
    #add ingredient 3 
except MissingIngredient: 
    try: 
     .... 
    except MissingIngredient: 
     .... 

    print 'you are missing ingredients' 

然而,可能是以下結構較好:

try: 
    #add ingredient 1 

    try: 
     #add ingredient 2 

     try: 
      #add ingredient 3 

      # Here you can assume ingredients 1, 2 and 3 are available. 

     except MissingIngredient: 
      # Here you know ingredient 3 is missing 

    except MissingIngredient: 
     # Here you know ingredient 2 is missing 

except MissingIngredient: 
    # Here you know ingredient 1 is missing 
+0

這不是問題的答案。 –

0

事實並非如此。它應該立即從try子句中移除except子句;我知道繼續下去的唯一途徑是某種嘗試...除外......終於......

相關問題