c# - 在 .NET 中,finally 是否等同于 try-catch-throw?

标签 c# .net cil

我正在为 CIL 编写一个静态分析工具。如果 finally block 可以解释为在 catch 中重新抛出的 try-catch block ,则控制流分析将得到简化。 在 C# 中,我看不出

之间的区别
try
{
    // ...
}
finally
{
    // finally code here
}

try
{
    // ...
}
catch
{
    // finally code here
    throw;
}

或之间

try
{
    // ...
}
catch(Exception e)
{
    // catch code here
}
finally
{
    // finally code here
}

try
{
    try
    {
        // ...
    }
    catch (Exception e)
    {
        // catch code here
    }
}
catch
{
    // finally code here
    throw;
}

CIL 中甚至还有 finally block 和 endfinally 指令。一定有区别,是吗?

最佳答案

否 - 即使没有抛出异常,也会执行 finally block ,即使另一个 catch block 捕获了异常,也会执行 。 (无论 catch block 本身是否抛出异常,都是如此。)

哦,如果 try block 从该方法返回,finally block 将执行。

基本上,如果您希望代码在执行离开语句时始终执行,finally 就是您想要的。尽管在 C# 中,我发现我很少编写显式的 finally block - using 语句几乎总能使代码更简单。

关于c# - 在 .NET 中,finally 是否等同于 try-catch-throw?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496104/

相关文章:

c# - TCP 套接字上的 XML

c# - 调用基本构造函数 C# 时出错

c# - 带参数的 AutoMapper 依赖注入(inject)

.net - 如何自定义构建和发布过程

c# - 了解 C# 编译器如何处理链接 linq 方法

vb.net - 什么是反编译的 VB 中的 __PostIncrement(通过 ILSpy)

c# - 在 Google URL Shortener API 调用中获取 System.Net.WebException : The remote server returned an error: (403) Forbidden.

c# - 如何防止 Entity Framework 加载所有子对象

c# - xml,xmlreader使用c#只读特定部分

C# 通用对象函数指针,相同地址?