c# - 在 Try/Catch block 中使用 Response.Redirect(url)

标签 c# .net try-catch response.redirect

如果我对 try/catch block 中的错误的响应是将用户重定向到错误页面,则 try/catch block 的行为就好像有错误,而实际上没有。如果我将其更改为执行其他操作,则代码可以正常工作。

例子:

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.
}

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

这是怎么回事?

最佳答案

当您使用 Response.Redirect 时,会抛出 ThreadAbortException。因此,为了获得您所描述的结果,您需要按如下方式修改代码:

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

}
catch(Exception e)
{
  // Catch other exceptions
  Response.Redirect("~/myErrorPage.aspx");
}

关于c# - 在 Try/Catch block 中使用 Response.Redirect(url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12358535/

相关文章:

javascript - 在 ASP 中调用 JavaScript 函数 :TEXTBOX

c# - Nancy FX 在模型绑定(bind)上将字典中的键大写

.net - 什么是IL编织?

C++ Try Catch block 不捕获异常

c# - Cosmos DB 更改源监控与轮询

c# - 使用 protobuf-net 在 WCF 中序列化数组

c# - 关于流的一些事

接收 cpp/cli 对象的 C# 类构造函数导致错误 'not supported by the language'

java - try-catch找不到符号问题

r - 如何加速 R 中的 tryCatch 函数?