开发者

Will code in finally run after a redirect?

Take for example the following code:

   try
   {
      Response.Redirect(someurl);
    }
    fi开发者_如何学Pythonnally
    {
       // Will this code run?
    }

Will the code in the finally block run?


Yes.

Try it and see!


Simple enough to test:

try
{
  Response.Redirect(someurl);
}
finally
{
   File.WriteAllText("C:\\Temp\\test.txt", "The finally block ran.");
}


It will run. Response.Redirect actually throws a ThreadAbortException, so that's why code after that will not run (except anything in a finally block of course).


It will indeed. See this MSDN article: Finally always executes


The code in the finally will run, but it will run before the redirect, since the redirect won't be sent to the browser until the method returns, and the finally code will execute before the method returns.


Try this:

try
{
  Response.Redirect("http://www.google.com");
}
finally
{
   // Will this code run?
  // yes :)
  Response.Redirect("http://stackoverflow.com/questions/3668422/will-code-in-finally-run-after-a-redirect");

}


Why do you not just try it?

finally always runs, except in these extreme scenarios:

  • Total application crash, or application termination (e.g. FailFast())
  • A limited number of serious exceptions
  • Threads getting terminated (eg. Thread.Abort())
  • Hardware failure (e.g. machine losing power)
  • Infinite loop inside the try-block (which ultimately results in application termination)


Yes. Code in the finally is guaranteed to run, unless something catastrophic happens.


Yes. Here is how you can check if I am right or not. Simply place a message box or write something to the console from finally and you will have your answer.


The general rule is that the code in finally will be applied in all cases (try/catch)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜