2011-01-25 31 views
60

比方说,我们有一个结构,像这样:嵌套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块这样的鼓励,但我无法找到任何具体原因。

这是错的代码?如果是这样,为什么?

+2

不确定片段真的有多准确。但是当你抓到异常时,你并不知道你真的知道了什么。它可以是*任何*。考虑利用VB.NET支持的When子句。 – 2011-01-26 00:07:19

回答

63

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

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 
+7

登录后台线程是我将使用内部try/catch的地方。我不希望这个方法结束,因为它不能记录它在做什么。 – gooch 2011-01-25 22:56:04

+0

@Gooch真的,我也这么做,我会将它添加到我的答案中。 – Basic 2011-01-25 22:59:27

31

其实我不认为有什么本质上错嵌套Try/Catch块,但他们可能很难浏览,并有可能,你可以做一些重构(内标志例如,10/Catch转化为它自己的方法)。

但我确实想解决此评论:

' Outer try code, that can fail with more generic conditions, 
' that I know less about and might not be able to handle 

如果你不知道如何在特定情况下处理异常,相信我:抓住他们。最好让你的应用程序崩溃(我的意思是,你知道,它只是不要吞下去),而不是去捕捉你不知道如何恢复的东西,然后让你的应用程序继续在损坏的状态。从这一点上看,行为最好是不可预测的。

相关问题