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

Gor*_*oro 77 .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
Run Code Online (Sandbox Code Playgroud)

我已经看到一些意见认为这样的嵌套Try块是不鼓励的,但我找不到任何具体的原因.

这是坏代码吗?如果是这样,为什么?

Bas*_*sic 81

在某些情况下,它们是个好主意,例如对整个方法进行一次try/catch,在循环内进行另一次尝试/ 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
Run Code Online (Sandbox Code Playgroud)

我们还在错误处理例程中使用嵌套的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
Run Code Online (Sandbox Code Playgroud)

  • 登录后台线程是我将使用内部try/catch的地方.我不希望该方法结束,因为它无法记录它正在做什么. (7认同)

Dan*_*Tao 36

我实际上并不认为嵌套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
Run Code Online (Sandbox Code Playgroud)

如果您不知道如何在特定情况下处理异常,请相信我:不要抓住它们.最好让你的应用程序崩溃(我的意思是,你知道,记录它;只是不要吞下它),而不是抓住你不知道如何从中恢复的东西,然后让你的应用程序在腐败状态下继续快速继续.从那时起,行为最多是不可预测的.

  • @Goro:在这种情况下,我会推荐一个app范围的异常处理机制(例如,如果这是WinForms,处理`Application.UnhandledException`事件)而不是per-method`Try` /`Catch`块. (10认同)