Karl Seguin

Sponsors

The Lounge

Wicked Cool Jobs

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Should Response.Redirect really throw an exception?
Every now and again, we get a question in the newsgroup asking why they are getting a ThreadAbortException. Code is provided, and 99% of the time a Response.Redirect is always the culprit.

I've answered this atleast 10 times without really thinking about it - though I always make sure to give a thorough explanation. (I just woke up, but i'm pretty sure it's REsponse.End() that throws the exception, which is called internally by Response.Redirect()).

Today though, for some reason, it seems really wrong that Response.Redirect throws an exception. What's worse is that one of the overloads, Response.Redirect(string path, bool end); doesn't. I see two problems here. First of all, it really isn't an exception situtation? People call Response.End() and Response.Redirect() all the time - heck, they are public functions! You are guaranteed that calling these public functions will result in an exception - doesn't seem right.

The 2nd problem is that an overload of Response.Redirect() doesn't generate an exception. Obviously it's alright for overloads to behave differently, for example:

public static DoSomething(Page page)
{
}
public static DoSomething()
{
   if (HttpContext.Current == null || !(HttpContext.Current.Handler is Page)
  {
        //throw exception..
  }
  DoSomething(HttpContext.Current.Handler);
}

But for one of them to _always_ throw an exception just seems wrong (reading over that I'm not sure there's a difference between my 1st point and my 2nd point, but whatever)...

I imagine the reason the exception is thrown is for some deep design reason needed by the ASP.NET framework. Insight would be welcomed...





Posted Thu, May 18 2006 8:05 AM by karl
Filed under:

[Advertisement]

Comments

Colin Blair wrote re: Should Response.Redirect really throw an exception?
on Thu, May 18 2006 9:47 AM
Remember, Response.Redirect(url) is the same as Response.Redirect(url,True). It isn't the overload that stops the exception, it is passing False to the overload that stops the exception. If you pass True, or don't pass the boolean at all, then you are telling Response.Redirect to go to this other page and stop processing of this page/thread. ThreadAbortException isn't a regular exception, it is a special one that automatically rethrows itself if you try to catch it. So, all of your code accordians all the way back down the stack allowing cleanup to occur, TransactionScopes to rollback, etc.

That is a long way to say, maybe you should read the documentation on Response.Redirect and ThreadAbortException where all of this is explained.
karl wrote re: Should Response.Redirect really throw an exception?
on Thu, May 18 2006 10:32 AM
I'm not saying it isn't documented. I'm saying that redirecting isn't an exceptional situation. There might be good framework justifications for the way it works, but there's no reason for the consumer to be notified, via exception, that what was asked for worked as expected. Isn't it akin to asking for a substring and having it raise the "EverythingWorkedOk" exception?

Like I said, I'm sure it's implemented this way because it has to be, but I still don't think the exception should bubble out of the function call. Maybe it has to, but it shouldn't
anon wrote re: Should Response.Redirect really throw an exception?
on Thu, May 18 2006 10:42 AM
it's done like that so that .net can then create a new http request with a 302 code to show that it's a temporary move.

see http://pubs.logicalexpressions.com/pub0009/LPMArticle.asp?ID=214 for an exhaustive description
Sam Smoot wrote re: Should Response.Redirect really throw an exception?
on Thu, May 18 2006 7:41 PM
So maybe it's just a bad name and shouldn't be called an Exception?
Larry wrote re: Should Response.Redirect really throw an exception?
on Thu, May 18 2006 8:13 PM
This gets worse in .NET 2.0.  In ASP.NET 2.0, an unhandled exception will bubble up and crash your webapp/app pool and clear all your users' sessions.  Since you can't catch one of these ThreadAbortExceptions, it means that any time you have a Redirect inside a Try/Catch, you just killed your app.
John S. Reid wrote re: Should Response.Redirect really throw an exception?
on Thu, Oct 12 2006 1:42 PM

You don't need to put the redirect in a try-catch block.  Just replace all calls to Response.Redirect(url) with the following two lines:

Response.Redirect(url, false);

HttpContext.Current.ApplicationInstance.CompleteRequest();

That will avoid the exception being thrown and gracefully end execution of the thread and event chain.  See http://www.c6software.com/CodeSolutions/dotnet/ThreadAbortException.aspx for a full solution explanation.

Andy wrote re: Should Response.Redirect really throw an exception?
on Mon, Dec 4 2006 11:22 AM

It also seems that to the response.redirect(url, true)  will execute all code until the page is loaded this also means if you redirect in the Page.Load and have another redirect in say a button clicked the clicked button will always redirect and the page.load will be ignored.

To me this seems a little daft sometimes I may wish to stop the page response before loading and and exception will occur each time. An example could be a large generated report that executes on page load but the user session is logged out this means I will have to wait for the report to load before the redirect will occur in this instance the page should redirect first and not cause a exception.

I know what you will say, that you should check the session prior to loading the report bit say I say fair enough but 1 line of code is better than checking at every possible avenue where a event may happen.

John S. Reid wrote re: Should Response.Redirect really throw an exception?
on Sat, Jan 6 2007 10:22 AM

Hi Andy,

You're correct, but my article addresses those concerns in a much simpler fashion also.  There is a quick and easy way to keep the click redirect from firing if there is a redirect in the Page_Load and you won't have to spread checks throughout the code.  And there isn't any messing with session variables or state either. Check it out!

John

bepenfriends wrote re: Should Response.Redirect really throw an exception?
on Fri, Mar 2 2007 5:38 AM

Hi friends,

I am not a experienced asp.net programmer but a learner.

If we use response.redirect(url,false) it is executing the complete function/subroutine till the end. To avoid that we can use the below work around

Response.redirect (lStrURL,false)

exit sub

Response.redirect (lStrURL,false)

exit function

Thus we are stopping the further processing. This is just a work around but i strongly recommond the MS to change the method of redirect and transfer calls. If there is any content in response buffer then throwing an error is fine.

When there is no error it must never throw any error.

Albert

http://www.bepenfriends.com/

wrong wrote re: Should Response.Redirect really throw an exception?
on Tue, Jun 26 2007 7:58 PM

you are wrong bepenfriends, put a stop on your code and watch it execute twice with the code you supplied

mikey wrote re: Should Response.Redirect really throw an exception?
on Wed, Aug 15 2007 3:17 PM

It shouldn't throw the exception, but it was a quick hack to make things work right -- basically the hack is the bubbling, uncatchable exception -- it just keeps bubbling out to get out of your page -- exit function won't help either, because further events can still be processed on the page.

What you can do is this:

Dim Redirect as Boolean = False

try

'do my stuff

if something then Redirect=true

catch

end try

if Redirect then Response.Redirect(url)

--- basically the idea is to move it outside of the try catch.  Ugly, but it works.

Jon Sagara wrote re: Should Response.Redirect really throw an exception?
on Tue, Sep 18 2007 11:25 AM

Perhaps not, but there is nothing wrong with it.  You just have to be aware of the consequences of placing your Response.Redirect() call within a try/catch.

www.jonsagara.com/.../response-redirect-and-the-threadabortexception-and-why-it-s-a-good-thing.aspx

All About Response.Redirect « Maverick wrote All About Response.Redirect « Maverick
on Wed, Oct 24 2007 6:36 AM

Pingback from  All About Response.Redirect « Maverick

Chuck Snyder wrote re: Should Response.Redirect really throw an exception?
on Wed, Nov 26 2008 1:22 PM

Ahha, gota love the internet.

thanks for the help, while the rediret wasn't causing the program to crash, its nice to have the errors cleaned up.

Thanks again.

2.0: unexpected exception "Thread was being aborted" | keyongtech wrote 2.0: unexpected exception "Thread was being aborted" | keyongtech
on Thu, Jan 22 2009 12:12 AM

Pingback from  2.0: unexpected exception "Thread was being aborted" | keyongtech

Devlicio.us