Nov 18 2005

What’s this ThreadAbortException?

Published by sethyates at 7:09 am under Development, Quality

Quite often when developers are developing ASP.NET applications and they’ve added exception handling, they will have some code like the following:

try
{
...
Response.Redirect("/default.aspx", true);
}
catch (Exception exc)
{
... // proper exception handling.
}

Funny thing is, many developers don’t realise it, but Response.Redirect throws a ThreadAbortException, which gets caught by the catch filter.

What’s the right way to handle this? I can outline three ways, each of which may be applicable in a given scenario:

  1. Simple. Move the Response.Redirect outside the try/catch statement. Problem solved. The catch filter will not receive the exception.
  2. Follow some exception handling best practices and only catch the exception type you really know how to handle:

    try
    {
    ...
    Response.Redirect("/default.aspx", true);
    }
    catch (ArgumentOutOfRangeException exc)
    {
    ... // proper exception handling.
    }
  3. Catch the ThreadAbortException and rethrow it:

    try
    {
    ...
    Response.Redirect("/default.aspx", true);
    }
    catch (ThreadAbortException)
    {
    throw;
    }
    catch (Exception exc)
    {
    … // proper exception handling.
    }

Hope that’s answered “why am I getting a ThreadAbortException?” and given you some ideas of how to work around it.

ASP.NET, web development, exception management

Related posts

Comments are closed at this time.

Trackback URI |