我正在为一个朋友检查一些代码,并说他在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
  }
}

当前回答

这里有一个小测试:

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

其他回答

引用自MSDN

Finally用于保证执行语句代码块,而不管前面的try块是如何退出的。

它也不会触发未捕获的异常,并运行在Windows服务托管的线程中

Finally在运行在Windows服务中的线程中不执行

是的。这实际上是最后一个陈述的主要观点。除非发生了一些灾难性的事情(内存不足,计算机拔插等),finally语句应该始终执行。

这里有一个小测试:

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

我意识到我迟到了,但在确实抛出异常的场景(与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.