微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.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 / 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

原文地址:https://www.jb51.cc/vb/256477.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐