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 TryCatch outerEx as Exception ' Handle outer exceptionEnd Try
我看到一些意见,嵌套尝试块这样是不鼓励,但我找不到任何具体原因。
这是坏的代码?如果是,为什么?
在某些情况下,他们是一个好主意,例如。一个try / catch用于整个方法,另一个在循环内,因为您希望处理异常并继续处理集合的其余部分。真正的唯一原因是,如果你想跳过错误的位,继续,而不是解开堆栈和丢失上下文。在编辑器中打开多个文件是一个很好的例子。
也就是说,例外应该是 – 例外。程序应该处理它们,但尽量避免它们作为正常执行流程的一部分。它们在大多数语言中是计算上昂贵的(python是一个显着的例外)。
另一种有用的技术是捕获特定的异常类型…
Try 'Some code to read from a fileCatch 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 ThrowEnd 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总结
以上是内存溢出为你收集整理的.net – 嵌套Try/Catch块是个坏主意吗?全部内容,希望文章能够帮你解决.net – 嵌套Try/Catch块是个坏主意吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)