简体   繁体   English

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

[英]What happens to the returned value after exception is thrown in finally block?

I wrote the following test code, even though I was pretty sure what would happen: 我写了下面的测试代码,尽管我很确定会发生什么:

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

Sure enough, the program wrote "False" to the console. 果然,该程序向控制台写了“False”。 My question is, what happens to the true that is originally returned? 我的问题是,最初返回的真实情况会发生什么? Is there any way to get this value, in the catch block if possible, or in the original finally block if not? 有没有办法获得这个值,如果可能的话,在catch块中,或者如果不是,在原始的finally块中?

Just to clarify, this is only for educational purposes. 只是为了澄清,这仅用于教育目的。 I would never make such a convoluted exception system in an actual program. 我永远不会在实际程序中制作这样一个复杂的异常系统。

No, it's not possible to get that value, because only a bool is returned, after all. 不,这是不可能获得该值,因为毕竟只返回一个bool You can set a variable, though. 但是,您可以设置变量。

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

It's messy, though. 但这很麻烦。 And for education purposes, the answer is no. 出于教育目的,答案是否定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM