Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will code in finally run after a redirect?

Tags:

c#

asp.net

Take for example the following code:

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

Will the code in the finally block run?

like image 565
Shiraz Bhaiji Avatar asked Sep 08 '10 13:09

Shiraz Bhaiji


People also ask

Will code execute after response redirect?

Redirect(), code following it will not execute. If you think about it, it would make sense not to execute it. You're basically telling your code that you want to go somewhere else. Example: Think of it as ordering a value meal at McDonalds.

Does response redirect stop execution?

Response. Redirect("Default. aspx", true) means current page execution is terminated and page is redirected to the default.

Does finally block always execute in C#?

A finally block always executes, regardless of whether an exception is thrown.

Will finally be executed without exception?

A finally block is always get executed whether the exception has occurred or not. If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code.


2 Answers

Yes.

Try it and see!

like image 66
Neil Moss Avatar answered Nov 14 '22 02:11

Neil Moss


Simple enough to test:

try
{
  Response.Redirect(someurl);
}
finally
{
   File.WriteAllText("C:\\Temp\\test.txt", "The finally block ran.");
}
like image 21
ChaosPandion Avatar answered Nov 14 '22 02:11

ChaosPandion