Response.Redirect inside of a Try/Catch

Ok, first off, let me state, that I am not entirely certain WHY I did this in the first place.  I am going to say I was rushed and wasn’t thinking clearly.  However, I glazed over it and moved on and when it came time to test, I was getting bizarre behavior that didn’t throw an error.

Session[“var”] = “”; 
try { 
    Session[“var”] = “Good Value”; 
    Response.Redirect(“newpage.html”); 
} 
catch(Exception ex) 
{ 
    Session[“var”] = “Bad Value”; 
}

In the code above, Session[“var”] will ALWAYS equal “Bad Value”.  Why you may ask?

Response.Redirect throws a ThreadAbortException.  … Fun, no?

If you are building a URL inside of a try block that you want to then redirect to, declare a string, build your url, and then pass that on to the Response.Redirect statement.

For Example:

string _url; 
try {
    _url = “yourpage.aspx?var=” + iffyMethodCall(); 
} 
catch(InvalidOperationException ex) 
{
    _url = “error.html”; 
} 
Response.Redirect(url);

So, If you ever run into odd behavior in a site you are working on and when debugging, your code goes straight past your Response.Redirect and into the catch block and the debugger starts giving you cryptic messages, this may be what you’re seeing.