我正在为一个朋友检查一些代码,并说他在try-finally块中使用了return语句。即使try块的其余部分没有触发,Finally部分中的代码仍然会触发吗?

例子:

public bool someMethod()
{
  try
  {
    return true;
    throw new Exception("test"); // doesn't seem to get executed
  }
  finally
  {
    //code in question
  }
}

当前回答

最后不会运行的情况下,如果你正在退出应用程序使用 system . exit (0);就像在

try
{
    System.out.println("try");
    System.exit(0);
}
finally
{
   System.out.println("finally");
}

结果将是: 试一试

其他回答

finally块的主要目的是执行写入其中的内容。它不应该取决于try或catch中发生的任何事情。但是使用System.Environment.Exit(1),应用程序将退出而不移动到下一行代码。

最后不会运行的情况下,如果你正在退出应用程序使用 system . exit (0);就像在

try
{
    System.out.println("try");
    System.exit(0);
}
finally
{
   System.out.println("finally");
}

结果将是: 试一试

简单的回答:是的。

我意识到我迟到了,但在确实抛出异常的场景(与OP的示例不同)中,MSDN声明(https://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx):“如果没有捕获异常,finally块的执行取决于操作系统是否选择触发异常unwind操作。”

The finally block is only guaranteed to execute if some other function (such as Main) further up the call stack catches the exception. This detail is usually not a problem because all run time environments (CLR and OS) C# programs run on free most resources a process owns when it exits (file handles etc.). In some cases it may be crucial though: A database operation half underway which you want to commit resp. unwind; or some remote connection which may not be closed automatically by the OS and then blocks a server.

这里有一个小测试:

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("before");
        Console.WriteLine(test());
        Console.WriteLine("after");
    }

    static string test()
    {
        try
        {
            return "return";
        }
        finally
        {
            Console.WriteLine("finally");
        }
    }
}

结果是:

before
finally
return
after