ThreadAbortException in Response.Redirect

27 04 2011

If you ASP.Net application has catch all error logging, don’t be surprised if you find ThreadAbortException [Exception message: The thread was being aborted] very often. The culprit could be the following code.

try

{


//Some error thrown


throw
new
DivideByZeroException();

}


catch (Exception ex)

{


//Some logging code here


//Finally redirect user to error page

Response.Redirect(“Error.aspx”,false);

}

The reason is that Response.Redirect end the current response by calling Response_End internally. Response_End always throws a ThreadAbortException by design. To avoid this you can do either of the following

  1. Catch the ThreadAbortException and call Thread.ResetAbort to cancel the abort. Do keep in mind that there is no guarantee that the thread will ever end.
  2. Ignore it. Which means, catch the exception; but do not log it.
  3. Finally, Response.Redirect takes two paramters. The URL itself and a Boolean parameter telling whether the current response should end or not. To avoid ending the current response, pass a Boolean value of false. So we can rewrite the above code as

    Response.Redirect(“Error.aspx”,false);

Advertisements