2013-10-01 26 views
4

我試圖做Python中的嵌套的try/catch塊來打印一些額外的調試信息:Python嵌套try/except - 引發第一個異常?

try: 
    assert(False) 
except: 
    print "some debugging information" 
    try: 
     another_function() 
    except: 
     print "that didn't work either" 
    else: 
     print "ooh, that worked!" 
    raise 

我想總是重新引發第一個錯誤,但似乎這個代碼,以提高第二個錯誤(被認爲「沒有工作」的那個)。有沒有辦法重新提出第一個異常?

+0

你想要做什麼? – karthikr

回答

3

raise,沒有參數,引發最後的異常。爲了得到你想要的行爲,把錯誤的變量,這樣就可以與異常,而不是提高:

try: 
    assert(False) 
# Right here 
except Exception as e: 
    print "some debugging information" 
    try: 
     another_function() 
    except: 
     print "that didn't work either" 
    else: 
     print "ooh, that worked!" 
    raise e 

不過請注意,你應該捕獲更具體的異常,而不是僅僅Exception

2

您應該捕獲變量中的第一個異常。

try: 
    assert(False) 
except Exception as e: 
    print "some debugging information" 
    try: 
     another_function() 
    except: 
     print "that didn't work either" 
    else: 
     print "ooh, that worked!" 
    raise e 

raise默認情況下會引發最後的異常。

0

raise引發最後捕獲的異常,除非您另有指定。如果您想重新初始化例外情況,則必須將其綁定到名稱以供日後參考。

在Python 2.x中:

try: 
    assert False 
except Exception, e: 
    ... 
    raise e 

在Python 3.X:

try: 
    assert False 
except Exception as e: 
    ... 
    raise e 

除非你正在編寫通用的代碼,你想趕上只有你已準備好處理異常與...所以在上面的例子中,你會寫:

except AssertionError ... :