假设我们有如下 struct :

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个街区,但我找不到任何具体原因.

这是不是错误的代码?若有,原因为何?

推荐答案

在某些情况下,它们是一个好主意,例如,一个try/catch用于整个方法,另一个在循环中,因为您希望处理异常并继续处理集合的其余部分.

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

也就是说,例外(顾名思义)应该是例外.程序应该处理它们,但作为正常执行流的一部分,尽量避免它们.在most种语言中,它们的计算成本很高(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

我们还在错误处理 routine 中使用嵌套的try/catch...

    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

.net相关问答推荐

Powershell机器令牌组

获取Ef-Core集合的DeleteBehavior

CLR如何在后台优化布尔比较操作?

为什么我在环境变量中有不同的值?

将日期时间转换为日期格式 dd/mm/yyyy

编译时禁用 Dll 文化文件夹

.NET 的 `Array.Sort()` 方法使用的排序算法是稳定的算法吗?

在 C# DllImport 中使用 32 位或 64 位 dll

重新启动(回收)应用程序池

C#:内存不足异常

如何将自定义 UserControl 显示为对话框?

LINQ 性能常见问题解答

图像与位图类

Convert.ToBoolean 和 Boolean.Parse 不接受 0 和 1

为什么使用 ImmutableList 而不是 ReadOnlyCollection?

是否有可用的 WPF 备忘单?

风格上的差异:IDictionary vs Dictionary

如何获取命名空间中的所有类?

如何在 C# 中处理 XML

捕获控制台退出 C#