Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65411

Will code in finally run after a redirect?

Take for example the following code:

   try
   {
      Response.Redirect(someurl);
    }
    finally
    {
       // Will this code run?
    }

Will the code in the finally block run?

Upvotes: 9

Views: 4249

Answers (10)

abelenky
abelenky

Reputation: 64702

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)

Upvotes: 3

Abdelrahman ELGAMAL
Abdelrahman ELGAMAL

Reputation: 434

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

Upvotes: 2

Zafer
Zafer

Reputation: 2190

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

}

Upvotes: 3

Ned Batchelder
Ned Batchelder

Reputation: 375654

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.

Upvotes: 3

Philippe Leybaert
Philippe Leybaert

Reputation: 171824

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).

Upvotes: 7

Dave McClelland
Dave McClelland

Reputation: 3413

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

Upvotes: 5

Christopher B. Adkins
Christopher B. Adkins

Reputation: 3567

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.

Upvotes: 2

Brian Genisio
Brian Genisio

Reputation: 48137

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

Upvotes: 2

ChaosPandion
ChaosPandion

Reputation: 78282

Simple enough to test:

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

Upvotes: 6

Neil Moss
Neil Moss

Reputation: 6848

Yes.

Try it and see!

Upvotes: 13

Related Questions