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

Actions

Information

One response

15 05 2011
toasty redhead

Good points

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: