c# - finally block 中抛出异常后的返回值会怎样?

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

果然,程序向控制台写入了“False”。我的问题是,最初返回的 true 会怎样?有没有什么方法可以获取这个值,如果可能的话在 catch block 中,如果不能的话在原始的 finally block 中?

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

最佳答案

不,不可能得到那个值,因为毕竟只返回一个 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;
    }
}

虽然很乱。出于教育目的,答案是否定的。

关于c# - finally block 中抛出异常后的返回值会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594013/

相关文章:

c# - Catch 提供的 URI 方案 'http' 无效;预期 'https' 错误

Powershell Try Catch 在高阶函数中

c# - 在由多个 View 模型绑定(bind)的 View 中绑定(bind)图像不起作用

google-apps-script - 在 Google Apps 脚本中,如何保留用户输入的换行符?

Javascript 返回冒号

node.js - 如何防止 node.js 崩溃?尝试捕捉不起作用

c# - 灯具对属性自动生成的约束

c# - 入口后面带有 Azure OAuth 的 ASP.NET Core MVC 进入无限登录循环

c# - 如何在 NEST 中附加两个 SearchDescriptors

Python:我的 Return 语句始终返回 None