在Try/Catch Block中使用Response.Redirect(url)

Nat*_*kle 2 .net c# response.redirect try-catch

如果我对try/catch块中的错误的响应是将用户重定向到错误页面,则try/catch块的行为就像没有时出现错误一样.如果我改变它做其他事情,代码工作正常.

例:

try
{
    //do this SQL server stuff
}
catch
{
   Response.Redirect(error.htm)
   //Change this to lblErr.Text = "SQL ERROR"; and the code in try works fine.
}
Run Code Online (Sandbox Code Playgroud)

从另一篇文章我了解到,Response.Redirect()方法有一个布尔重载.我尝试了true和false,并且try/catch块仍然表现得好像有错误.

这是怎么回事?

Jos*_*hua 10

当你的Response.Redirect,抛出一个ThreadAbortException.因此,要获得您所描述的结果,您需要修改代码,如下所示:

try  
{
   // Do some cool stuff that might break
}
catch(ThreadAbortException)
{

}
catch(Exception e)
{
  // Catch other exceptions
  Response.Redirect("~/myErrorPage.aspx");
}
Run Code Online (Sandbox Code Playgroud)