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

abo*_*u00 9 c# return try-catch

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

果然,该程序向控制台写了"False".我的问题是,最初返回的真实情况会发生什么?有没有办法获得这个值,如果可能的话,在catch块中,或者如果不是,在原始finally块中?

只是为了澄清,这仅用于教育目的.我永远不会在实际程序中制作这样一个复杂的异常系统.

Ry-*_*Ry- 5

不,这是不可能获得该值,因为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这很麻烦.出于教育目的,答案是否定的.

  • 这在VB.NET中实际上很有意思,其中为您预定义了本地变量返回结果`Test`.我刚刚测试了它,它在等效的`Catch`块中是'True`,即使在内部`Try`块中只使用`Return True`.当然,函数返回"False". (3认同)
  • @MarkHurd:这很有意思.我需要在某处使用:)嗯...... (2认同)