即使 try 块没有抛出异常,也会执行 catch 块

本文关键字:执行 catch 抛出异常 try 即使 | 更新日期: 2023-09-27 18:35:16

我正在尝试通过goDaddy邮件服务器发送邮件。邮件正在发送(我在我的邮箱中收到它),但 catch 块正在执行并将我登陆到查询字符串 msg 为"失败"的联系页面

    protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["username"] != null && Request.QueryString["email"] != null && Request.QueryString["msg"] != null)
    {
        try
        {
            string name = Request.QueryString[0];
            string email = Request.QueryString[1];
            string msg = Request.QueryString[2];
            SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net", 25);
            //smtp.EnableSsl = false;
            smtp.Send("feedback@solutionpoint98.com", "b.soham1991@gmail.com", "feedback", "Name:" + name + "'n e-mail:" + email + "'n Subject:" + msg);
            Response.Redirect("contact.html?msg=success");
        }
        catch(Exception ex)
        {
            Response.Redirect("contact.html?msg=fail");
        }
    }
    else
    {
        Response.Redirect("contact.html");
    }
}

如果正在发送邮件,它不应该重定向到"contact.html?msg=success"吗?

即使 try 块没有抛出异常,也会执行 catch 块

问题是你的第一个 Response.Redirect() 实际上抛出了一个 ThreadAbortException。这是因为.重定向在内部调用 Response.End 方法,在这种情况下过早地结束 Response。

执行此操作的正确方法是使用重载的 Response.Redirect(string url, bool endResponse),它允许您通过将 endResponse 设置为 false ...这将防止引发此错误。

这篇 MS 支持文章涵盖了所有这些内容:http://support.microsoft.com/kb/312629/EN-US/

只需将代码修改为如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["username"] != null && Request.QueryString["email"] != null && Request.QueryString["msg"] != null)
    {
        try
        {
            string name = Request.QueryString[0];
            string email = Request.QueryString[1];
            string msg = Request.QueryString[2];
            SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net", 25);
            //smtp.EnableSsl = false;
            smtp.Send("feedback@solutionpoint98.com", "b.soham1991@gmail.com", "feedback", "Name:" + name + "'n e-mail:" + email + "'n Subject:" + msg);
            Response.Redirect("contact.html?msg=success", false);
        }
        catch(Exception ex)
        {
            Response.Redirect("contact.html?msg=fail", false);
        }
    }
    else
    {
        Response.Redirect("contact.html", false);
    }
}