嵌套try / catch块一个坏主意? [英] Are nested Try/Catch blocks a bad idea?

查看:891
本文介绍了嵌套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 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

这篇关于嵌套try / catch块一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆