加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.net – 嵌套Try/Catch块是个坏主意吗?

发布时间:2020-12-17 08:13:56 所属栏目:百科 来源:网络整理
导读:假设我们有这样的结构: 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 ab
假设我们有这样的结构:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读