C# 在finally块中抛出异常后,返回值会发生什么变化?

C# 在finally块中抛出异常后,返回值会发生什么变化?,c#,return,try-catch,C#,Return,Try Catch,我编写了以下测试代码,尽管我非常确定会发生什么: static void Main(string[] args) { Console.WriteLine(Test().ToString()); Console.ReadKey(false); } static bool Test() { try { try { return true; } finally {

我编写了以下测试代码,尽管我非常确定会发生什么:

static void Main(string[] args)
{
    Console.WriteLine(Test().ToString());
    Console.ReadKey(false);
}

static bool Test()
{
    try
    {
        try
        {
            return true;
        }
        finally
        {
            throw new Exception();
        }
    }
    catch (Exception)
    {
        return false;
    }
}
果然,程序向控制台写入了“False”。我的问题是,最初返回的true会发生什么变化?是否有任何方法可以在catch块(如果可能)或原始finally块(如果没有)中获取此值


澄清一下,这只是为了教育目的。我决不会在实际的程序中创建这样一个复杂的异常系统。

不,不可能得到那个值,因为毕竟只返回一个
bool
。不过,您可以设置一个变量

static bool Test()
{
    bool returnValue;

    try
    {
        try
        {
            return returnValue = true;
        }
        finally
        {
            throw new Exception();
        }
    }
    catch (Exception)
    {
        Console.WriteLine("In the catch block, got {0}", returnValue);
        return false;
    }
}

不过很乱。出于教育目的,答案是否定的。

这在VB.NET中非常有趣,在VB.NET中,局部变量返回结果
Test
是为您预定义的。我刚刚测试了它,它在等效的
Catch
块中是
True
,即使在内部
Try
块中仅使用
Return True
。当然,
False
由函数返回。几乎是重复的: