finally块中抛出异常后返回的值会发生什么情况

本文关键字:什么情况 返回 抛出异常 finally | 更新日期: 2023-09-27 18:27:03

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

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块中?

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

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;
    }
}

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

相关文章: