2011-01-25 146 views
60

比方說,我們有一個結構,像這樣:嵌套Try/Catch塊是一個壞主意嗎?

Try 
    ' Outer try code, that can fail with more generic conditions, 
    ' that I know less about and might not be able to handle 

    Try 
    ' Inner try code, that can fail with more specific conditions, 
    ' that I probably know more about, and are likely to handle appropriately 
    Catch innerEx as Exception 
    ' Handle the inner exception 
    End Try 

Catch outerEx as Exception 
    ' Handle outer exception 
End Try 

我已經看到了一些觀點認爲嵌套Try塊這樣的鼓勵,但我無法找到任何具體原因。

這是錯的代碼?如果是這樣,爲什麼?

+2

不確定片段真的有多準確。但是當你抓到異常時,你並不知道你真的知道了什麼。它可以是*任何*。考慮利用VB.NET支持的When子句。 – 2011-01-26 00:07:19

回答

63

在某些情況下,他們是一個好主意,例如,一個try/catch爲整個方法,另一個爲循環內部,因爲您要處理異常並繼續處理集合的其餘部分。

真正做到這一點的唯一理由是,如果你想跳過錯誤和繼續的位,而不是展開堆棧並丟失上下文。在編輯器中打開多個文件就是一個很好的例子。

也就是說,例外應該就是這樣 - 例外。程序應該處理它們,但試圖避免它們作爲正常執行流程的一部分。在大多數語言中它們在計算上很昂貴(python是一個明顯的例外)。

另外一個技術,它可以被捕捉特定的異常類型有用......

Try 
    'Some code to read from a file 

Catch ex as IOException 
    'Handle file access issues (possibly silently depending on usage) 
Catch ex as Exception 
    ' Handle all other exceptions. 
    ' If you've got a handler further up, just omit this Catch and let the 
    ' exception propagate 
    Throw 
End Try 

正如評論所指出的古奇下面,我們也在我們的錯誤處理程序使用嵌套的try /漁獲.. 。

Try 
     Try 
      'Log to database 
     Catch ex As Exception 
      'Do nothing 
     End Try 

     Try 
      'Log to file 
     Catch ex As Exception 
      'Do nothing 
     End Try 
    Catch ex As Exception 
     'Give up and go home 
    End Try 
+7

登錄後臺線程是我將使用內部try/catch的地方。我不希望這個方法結束,因爲它不能記錄它在做什麼。 – gooch 2011-01-25 22:56:04

+0

@Gooch真的,我也這麼做,我會將它添加到我的答案中。 – Basic 2011-01-25 22:59:27

31

其實我不認爲有什麼本質上錯嵌套Try/Catch塊,但他們可能很難瀏覽,並有可能,你可以做一些重構(內標誌例如,10/Catch轉化爲它自己的方法)。

但我確實想解決此評論:

' Outer try code, that can fail with more generic conditions, 
' that I know less about and might not be able to handle 

如果你不知道如何在特定情況下處理異常,相信我:抓住他們。最好讓你的應用程序崩潰(我的意思是,你知道,它只是不要吞下去),而不是去捕捉你不知道如何恢復的東西,然後讓你的應用程序繼續在損壞的狀態。從這一點上看,行爲最好是不可預測的。

相關問題