Will code in a Finally statement fire if I return a value in a Try block?

I'm reviewing some code for a friend and say that he was using a return statement inside of a try-finally block. Does the code in the Finally section still fire even though the rest of the try block doesn't?

Example:

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

简单的回答:是的。


Normally, yes. The finally section is guaranteed to execute whatever happens including exceptions or return statement. An exception to this rule is an asynchronous exception happening on the thread ( OutOfMemoryException , StackOverflowException ).

To learn more about async exceptions and reliable code in that situations, read about constrained execution regions.


Here's a little test:

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

The result is:

before
finally
return
after
链接地址: http://www.djcxy.com/p/21124.html

上一篇: 为什么我不应该在“尝试”中包装每个块

下一篇: 如果我在Try块中返回一个值,会在Finally语句中编写代码吗?