c00000fd
c00000fd

Reputation: 22255

Response.Redirect exception inside the try/catch block

Say, I have a try/catch block that encapsulates a large block of code and then somewhere in it I need to call Response.Redirect as such:

protected void ButtonGo_Click(object sender, EventArgs e)
{
    try
    {
        using(lockingMethod)
        {
            //Code...

            //Somewhere nested in the logic
            Response.Redirect(strMyNewURL);

            //More code...
        }
    }
    catch(Exception ex)
    {
        LogExceptionAsError(ex);
    }
}

What happens in this case is that Response.Redirect throws an exception, something about terminating the thread, which I believe is a "normal flow of events" for that method, but it gets logged in my LogExceptionAsError as an error. So I was curious, is there any way to make Response.Redirect not throw exception?

Upvotes: 12

Views: 12111

Answers (2)

Haney
Haney

Reputation: 34762

Response.Redirect accomplishes termination of the current execution and thus immediate redirection via throwing this exception such that it is unhandled. This is intentional and by design. You should not be catching it yourself in most cases - it defeats the purpose. If you wish to complete executing your code before redirecting, you can use the overload:

Response.Redirect(somewhere, false);

Which will NOT raise the exception. This could be inefficient unless you NEED to do something else before redirecting.

Note that this is generally an anti-pattern - controlling logic flow via exception throwing and catching... However it makes sense for this particular method to do so since a redirect usually requires no further logic to execute - just responds with a 302 and the new address to go to.

Upvotes: 6

sarwar026
sarwar026

Reputation: 3821

Try with alternative version of Response.Redirect

Response.Redirect(strMyNewURL, false);

It will terminate the current page loading.

Upvotes: 9

Related Questions