Dot-Net
嵌套的 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不鼓勵像這樣嵌套塊,但我找不到任何具體原因。這是壞程式碼嗎?如果是這樣,為什麼?
在某些情況下它們是一個好主意,例如整個方法的一次嘗試/擷取和循環內的另一個,因為您想要處理異常並繼續處理集合的其餘部分。
真正這樣做的唯一原因是如果您想跳過出錯的位並繼續,而不是展開堆棧並失去上下文。在編輯器中打開多個文件就是一個例子。
也就是說,異常應該(顧名思義)是異常的。程序應該處理它們,但盡量避免它們作為正常執行流程的一部分。在大多數語言中,它們的計算成本很高(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/catch …
Try Dim Message = String.Format("...", ) 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