views:

499

answers:

4

Response.Redirect has two overloads:

public void Redirect(string url)

Parameters:
url: The target location.
public void Redirect(string url, bool endResponse)
Parameters:
url: The location of the target.
endResponse: Indicates whether execution of the current page should terminate.

If I call the first overload, or call the second with endResponse set to true a ThreadAbortException gets thrown.

Why would I ever want to use this approach? Isn't this an example of using exceptions to handle program flow? (and therefore a bad thing)

And if my redirection did warrant an exeption, wouldn't it be preferable for me to throw a more informative exception that includes the reason for the redirect?

+1  A: 

I think the theory behind it is to avoid wasting horsepower. If you decide 5 function calls deep during a request cycle that a redirect is appropriate, then you'd need some way to signal to all of the higher level functions "we're done, don't waste any more time on this request", and asp.net itself would also need to do this.

I think the asp.net team took this approach rather than a) Using the function's return value (this meaning that if a function has a logical return value, that would have to be dealt with through Ref/Out parameters), or b) Setting a flag on the request. Sure, ASP.Net itself would be written to honour the flag, but how many beginner developers would cotton on that they should check it (after every function call?), and so they might still do some heavy-weight work that's going to be wasted.

Damien_The_Unbeliever
+2  A: 

If you set endResponse to "true", you are effectively saying "I am done with this page, ignore anything after me".

The reason a "ThreadAbortException" is raised is so that any Finallys/Catches etc that you have written are fired, and resources are correctly cleaned up before you are sent to the next page.

From MSDN:

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread.

Zhaph - Ben Duguid
+1  A: 

Sometimes exceptions are the best way to control the flow of your program.

Of course, usually that's not the case. So if you ever find yourself using exceptions for control flow, double-check that that there are no better alternatives.

An exception on Response.Redirect to abort the current thread often is a good thing, because that's exactly what you want to happen.

Justice
+2  A: 

Zhaph is right, that exception is occuring because you are redirecting in a try catch block.

Instead of

try {
    ...
    Response.Redirect(url);
} catch {
    ...
}

Do something along these lines:

bool bSuccess = true;
try {
    ...
} catch {
    bSuccess = false;
    ...
}

if (bSuccess) {
    Response.Redirect(url);
}
MikeW