嵌套try / catch块一个坏主意?坏主意、嵌套、try、catch

由网友(莂說丶対罘⑦)分享简介:让我们说我们有一个结构,像这样:Let's say we have a structure like so:Try' Outer try code, that can fail with more generic conditions, ' that I know less about and might not...

让我们说我们有一个结构,像这样:

Let's say we have a structure like so:

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

我已经看到了一些观点认为嵌套尝试这样的块气馁,但我无法找到任何具体原因。

I have seen some opinions that nesting Try blocks like this is discouraged, but I could not find any specific reasons.

这是不好的code?如果是这样,为什么?

Is this bad code? If so, why?

推荐答案

有某些情况下,他们是一个不错的主意,比如和一个的try / catch整个方法,你要处理的异常,并继续处理的集合/列表中的其余部分环路内的另一个

There are certain circumstances where they're a good idea, e.g. one try/catch for the whole method and another inside a loop as you want to handle the exception and continue processing the rest of a collection/list

真的是唯一的理由这样做是,如果你想跳过出错的位和进行,而不是展开堆栈,失去语境。打开多个文件,在编辑器就是一个很好的例子。

Really the only reason to do it is if you want to skip the bit that errored and carry on, instead of unwinding the stack and losing context. Opening multiple files in an editor is a good example.

不过,异常应该只是 - 个例外。一个程序应该处理它们,但尽量避免他们作为正常的执行流程的一部分(它们是计算昂贵的最的语言)

That said, exceptions should be just that - exceptional. A program should handle them but try to avoid them as part of normal execution flow (they're computationally expensive in most languages)

另外一个技术,它可以是有用的就是捕捉特定的异常类型...

One other technique which can be useful is catching specific exception types...

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 or just re-throw as you're unlikely to know what to do
    Throw
End Try

由于在评论中指出,由古奇下面,我们还可以使用嵌套的try /我们的错误处理程序捕获...

As pointed out by Gooch in the comments below, we also use nested try/catches in our error handling routines...

    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
阅读全文

相关推荐

最新文章