Tuesday, June 9, 2009

Problem using Response.Redirect and Response.End in Try/Catch block

If we are using Response.End or Response.Redirect statements in TRY/CATCH block, code in catch block is still executed.

ASP.NET executes these 2 methods on Response object by throwing ThreadAbort Exception. When written in simple Try/Catch block this results in Catch block catching this exception and processing code written in catch block. This causes unwanted code execution which is generally written in Catch block.

To resolve this, we should always handle ThreadAbort exception separately and do nothing if it is thrown.

// Your code
catch (ThreadAbortException exc)
// This should be first catch block i.e. before generic Exception
// This Catch block is to absorb exception thrown by Response.End or Response.Redirect
catch (Exception exc)
// Your actual error handling code

However we can avoid this scenerio in case of Response.Redirect. Response.Redirect fails within a Try catch block because the thread stops execution when it reaches this line and it could be avoided by specifying the endExecution optional parameter as false in the statement.

E.g., Response.Redirect("your redirection url", false);