嵌套的 Try/Catch 块是个坏主意吗? [英] Are nested Try/Catch blocks a bad idea?

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

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

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

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

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.

这样做的唯一原因是如果您想跳过出错的位并继续,而不是展开堆栈并丢失上下文.在编辑器中打开多个文件就是一个例子.

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 one example.

也就是说,异常应该(顾名思义)是异常的.程序应该处理它们,但尽量避免将它们作为正常执行流程的一部分.在大多数语言中,它们的计算成本很高(Python 是一个明显的例外).

That said, exceptions should (as the name implies) be exceptional. A program should handle them but try to avoid them as part of normal execution flow. They're computationally expensive in most languages (Python being one notable exception).

另一种有用的技术是捕获特定的异常类型...

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.
    ' If you've got a handler further up, just omit this Catch and let the 
    ' exception propagate
    Throw
End Try

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

We also use nested try/catches in our error handling routines...

    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

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

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