Redirects in Try-Catch-Finally

In the Psuedo below: 

     //Do Some Stuff
catch(Exception e)
     //Exception Handling stuff
     //Finally stuff

... I redirect in the try block. My question is does the code in the finally block still run?  This isn't necessarily a big issue in and of itself, but in the context of this question, there are some database connections happening in try, and connection closures happening in finally.  If finally does not get executed because of a redirect, then I'm leaving connections open.

I went through my code and put conditional redirects after the try-catch-finally blocks to be safe, but I was just curious if anyone knew how this is handled.

I never lose, some people are just better than me at winning.
10/30/2007 4:13:02 PM 91979 articles. 4 followers. Follow

4 Replies

Similar Articles

[PageSpeed] 5
Get it on Google Play
Get it on Apple App Store

The answer to your question is yes and no.  Yes, the finally block will execute, but only because an exception will occur on the Response.Redirect line.  A thread exception will occur because you are trying to redirect to another page before the try-catch block has reached its end.  In order to fix the exception, you should change the line to read, Response.Redirect("somefile.aspx", true/false);  The true/false argument instructs the code to continue or end execution of the current page before performing the redirect.

Jarell Lloyd
Senior Consultant
Xede Consulting Group
10/30/2007 6:14:30 PM

I've seen a number of people in other forums saying that it will.  But based on this Microsoft Knowledge Base Article for SharePoint services, it will not:

 "Calling Response.Redirect WILL NOT execute the finally block."

When your question has been sufficiently answered, please be sure to mark your question as answered. Also, please share your solution if you had to figure it out on your own!
10/30/2007 6:19:24 PM

 Mine actually executed just fine without throwing a thread exception, which is why I was concerned that maybe there would be some hanging connections.  Based on the article provided by
 sweeperg, it looks as my concerns might have been correct.  My solution, however, was slightly different in that I placed the redirect outside of the scope of the try-catch-finally block.


Thanks for the note on the true/false tag on redirect jarellxede.  I'll keep that in mind in the future.


I never lose, some people are just better than me at winning.
10/30/2007 8:37:28 PM

 I usually do what you did...

I set a "flag" in the try block

then outside the try/catch, i use this flag to do ( or not to do ) the redirect ( or whatever action you're trying) 

Hope That Helps
All that wander, are not lost...
What were we talkin bout
10/30/2007 8:44:27 PM