Response.Redirect cause Thread Aborted error

by Edward 25 August 2009 06:32

I came accross an old enemy of ASP.NET developers. In some cases you would click a button, do something and then redirect the user to another page, but then you might have an error along the lines of "Thread was being aborted" popup if you run the page in debug mode.

The main reason why this will happen is, is that you have your redirect in a try/catch block. This is not the way to do it.

There are a few ways around this error, however I am going to point out two easy ways to handle this error.

1) Use the Response.Redirect outside a try/catch block:

The Response.Redirect fails within a try/catch block, because the thread stops execution when it reaches this line and it could be avoided. It is better to do the Response.Redirect outside the try/catch block.


    try
    {
                 // Your actual code
    }
    catch (Exception ex)
    {
                // Catch the error, or Write actual error handling code here
        // Make sure the page returns or the error is handled from here or the next line will be read.
    }

    //Response.Redirect to next page
    Response.Redirect("About_Dascode.aspx");


2) Handle the exception:

You need to handle the "ThreadAbort" exception separately and do nothing if it is thrown. Also catch the ThreadAbortException before any other exceptions, otherwise the code will not catch the error and

    try
    {
                // Your code here

        // Redirect to another page
                Response.Redirect("About_Dascode.aspx");
    }
    catch (ThreadAbortException exc)
    {
                 // This should be first catch block i.e. before generic Exception
                 // This Catch block is to absorb exception thrown by Response.Redirect
    }
    catch (Exception ex)
    {
                // Write actual error handling code here
    }


Either way will be the correct way, however if you are not keen on handling the "ThreadAbort" exception, use the first option.

Tags: , , , ,

ASP.NET

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List