嵌套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块是不鼓励,但我找不到任何具体的原因。

这是不好的代码? 如果是这样,为什么?

在某些情况下,他们是一个好主意,例如整个方法的try / catch和循环内部的另一个,以便处理exception并继续处理集合的其余部分。

真的,唯一的理由就是如果你想跳过这个错误,继续进行,而不是解开堆栈,丢失上下文。 在编辑器中打开多个文件就是一个很好的例子。

也就是说,例外应该就是这样 – 例外。 程序应该处理它们,但是要尽量避免它们作为正常执行stream程的一部分。 在大多数语言中它们在计算上是很昂贵的(python是一个明显的例外)。

另一种可能有用的技术是捕获特定的exceptiontypes…

 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 

正如Gooch在下面的评论中指出的那样,我们也在我们的error handling例程中使用了嵌套try / catches。

  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 

我实际上并不认为嵌套的Try / Catch块有什么内在的错误,除了它们可能很难导航,并且可能是你可以做一些重构的一个标志(例如内部的Try / Catch ) 。

但是我想要解决这个问题:

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

如果你不知道如何处理特殊情况下的例外情况,请相信我: 不要抓住它们。 更好地让你的应用程序崩溃(我的意思是,你知道, logging它,只是不要吞下去),而不是赶上你不知道如何恢复的东西,然后让你的应用程序继续高兴地在损坏的状态。 从那时起,行为将是不可预测的。