c# - 在 C# 中,为什么在 finally block 的开头没有明确分配变量?

标签 c# try-catch

我不明白为什么下面的代码会产生错误。通常我可以从语言规范中弄明白,但在这种情况下我不理解语言规范。

顺便说一下,这不会导致我的代码出现问题,我只是想了解这门语言。

例子:

bool success;
try
{
    success = true;
}
catch
{
    success = false;
}
finally
{
    Console.WriteLine(success); // ERROR: Local variable 'success' might not be initialized before accessing
}

此行为似乎适用于所有 C# 版本,但下面的引用来自 C# Language Specification 5.0 .

第 5.3.3.14 节 Try-finally 语句

The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt.

这里“stmt 的开始”是指整个 try-finally 语句的开始,即在 try 之前。

5.3.3.15 节 Try-catch-finally 语句

The following example demonstrates how the different blocks of a try statement (§8.10) affect definite assignment.

static void F() {
    int i, j;
    try {
        goto LABEL;
        // neither i nor j definitely assigned
        i = 1;
        // i definitely assigned
    }
    catch {
        // neither i nor j definitely assigned
        i = 3;
        // i definitely assigned
    }
    finally {
        // neither i nor j definitely assigned
        j = 5;
        // j definitely assigned
    }
    // i and j definitely assigned
  LABEL:;
    // j definitely assigned
}

谁能解释为什么 success(在我的示例中)或 i(在语言规范示例中)没有在 finally block 的开头明确分配?

最佳答案

原因很简单 - 无法保证 trycatch block 中的代码会在 finally block 之前执行。

ThreadAbort 异常可能发生在 try block 内,但在赋值执行之前。

运行时代码在抛出异常之后但在 catch block 中的代码执行之前执行(搜索异常处理在 .Net 中的工作方式或“结构化异常处理”)。

因此,在执行 finally block 之前,try 和 catch block 中的代码可能永远不会执行。

关于c# - 在 C# 中,为什么在 finally block 的开头没有明确分配变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28755949/

相关文章:

c# - 在浏览器中运行 Windows 窗体

c# - 在不窃取焦点的情况下启动进程 (C#)

java - 在抛出异常之前从堆栈跟踪中删除最后一个方法

c++ - 尝试/捕获丢失的 vector 下标超出范围(调试断言失败)

python - python中的变量范围和Try Catch

php - 处理 php 页面错误的最佳方法?

C# 捕获 ThreadPool 上发生的异常

C# 从第二个线程绘制到位图

c# - 允许线程有序进入的WaitHandle.WaitAny

java - 当对象需要在 try/catch block 中时,IDE 的 "know"如何处理?