Wednesday, December 01, 2004 2:55 PM
by
brian
Response.Redirect and try/catch
Saw this post on The Daily WTF. I’ve seen a lot of developers handle Response.Redirect incorrectly with try/catch blocks.
You can read some of the discussions on the post, but for me, I simply don’t put a Response.Redirect in a try block. If I have to perform any operations to build the new url that may cause problems by failing, I’ll build a string in the try block. Then I’ll look for any exceptions that may arise in the catch blocks.
If everything goes well the catch blocks will be bypassed and the code will continue to the Response.Redirect below. Otherwise, I’ll probably create a different url in the catch block if it is a catastrophic error.
In case you didn’t know, Response.Redirect(url) always throws a ThreadAbortException.
string url;
try
{
url = "Page.aspx?id=" + DoSomethingDangerousToGetAnId();
}
catch(InvalidOperationException ex)
{
LogError(ex);
url = "Error.aspx?error=Something bad happened";
}
Response.Redirect(url);