【问题标题】:What happens to the returned value after exception is thrown in finally block?finally 块中抛出异常后返回的值会发生什么?
【发布时间】:2012-03-24 12:57:54
【问题描述】:

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

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

澄清一下,这仅用于教育目的。我永远不会在实际程序中制作如此复杂的异常系统。

【问题讨论】:

标签: c# return try-catch


【解决方案1】:

不,不可能得到那个值,因为毕竟只返回一个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 中实际上很有趣,其中为您预定义了局部变量返回结果 Test。我刚刚对其进行了测试,它在等效的Catch 块中是True,即使在内部Try 块中仅使用Return True。当然,False 是由函数返回的。
猜你喜欢
  • 2011-02-24
  • 2023-04-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
相关资源
最近更新 更多