Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
c00000fd Avatar asked Jul 02 '13 04:07

c00000fd


2 Answers

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.

like image 120
Haney Avatar answered Oct 24 '22 01:10

Haney


Try with alternative version of Response.Redirect

Response.Redirect(strMyNewURL, false);

It will terminate the current page loading.

like image 8
sarwar026 Avatar answered Oct 24 '22 01:10

sarwar026