嵌套的Try / Catch阻止了一个坏主意吗?

时间:2011-01-25 22:50:49

标签: .net vb.net exception-handling

假设我们有这样的结构:

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块,但我找不到任何具体原因。

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

2 个答案:

答案 0 :(得分:74)

在某些情况下,他们是个好主意,例如一个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

我们还在错误处理例程中使用嵌套的try / catches ...

    Try
        Dim Message = String.Format("...", )
        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

答案 1 :(得分:34)

我实际上并不认为嵌套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

如果你不知道在特定情况下如何处理异常,请相信我:不要抓住它们。最好让你的应用程序崩溃(我知道,你知道, log 它;只是不要吞下它),而不是抓住你不知道如何恢复的东西,然后让你的应用程序继续快乐在处于腐败状态的路上。从那时起,行为最多是无法预测的。