简体   繁体   中英

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?

Try with alternative version of Response.Redirect

Response.Redirect(strMyNewURL, false);

It will terminate the current page loading.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM