假设我们有这样的结构:
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 / 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
正如Gooch在下面的评论中指出的,我们还在我们的错误处理例程中使用嵌套的try / catch。
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