c# - ASP.Net C# - try-catch-finally 和 using 语句

标签 c# asp.net error-handling try-catch using

关闭。这个问题需要details or clarity .它目前不接受答案。












想改进这个问题?通过 editing this post 添加详细信息并澄清问题.

7年前关闭。




Improve this question




所以我已经习惯于使用 try-catch-finally 语句进行编码,而不包括 using 语句,我正在尝试将后者合并到我的代码中。

我在下面附上了我的原始代码和修改后的代码。本次修订是否足够?

此外,关于捕获错误,我在这里看到以下代码多次使用。什么时候应该使用/不使用它,因为这不会通知用户错误?

catch (Exception ex)
{
    throw ex;
}

原始代码:
protected void signIn()
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);

    MySqlCommand comm;
    comm = new MySqlCommand("Select user_id, username, email, salt, hashed_pw, role, activated FROM users WHERE username=@username", conn);
    comm.Parameters.Add("@username", MySqlDbType.VarChar);
    comm.Parameters["@username"].Value = txtUsername.Text;
    MySqlDataReader reader;

    try
    {
        conn.Open();
        reader = comm.ExecuteReader();

        if (reader.Read())
        {
            string saltAndPwd = String.Concat(txtPassword.Text, reader["salt"].ToString());
            string hashSaltAndPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");

            if (hashSaltAndPwd.Equals(reader["hashed_pw"].ToString()))
            {
                if (reader["activated"].ToString().Equals("Y"))
                {
                    Session["Username"] = reader["username"].ToString();
                    Session["Role"] = reader["role"].ToString();
                    Session["UserID"] = reader["user_id"].ToString();
                    Session["EmailAddress"] = reader["email"].ToString();

                    if (reader["role"].ToString().Equals("0"))
                    {
                        Session["PermanentRole"] = "admin";
                    }
                    else if (reader["role"].ToString().Equals("2"))
                    {
                        Session["PermanentRole"] = "tutor";
                    }

                    Response.Redirect("~/portal.aspx");
                }
                else
                {
                    lblError.Text = "Your account has not been activated.  Please check your inbox and activate your account or reset your password by clicking the link above.";
                }
            }
            else
            {
                lblError.Text = "Incorrect password.";
            }
        }
        else
        {
            lblError.Text = "Username does not exist.";
        }

        reader.Close();
    }
    catch
    {
        lblError.Text = "Database connection error. Please try again.";
    }
    finally
    {
        conn.Close();
    }
}

修改后的代码:
protected void signIn()
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        using (MySqlCommand cmd = conn.CreateCommand())
        {
            string cmdText = "Select user_id, username, email, salt, hashed_pw, role, activated FROM users WHERE username=@username";
            cmd.CommandText = cmdText;
            cmd.Parameters.Add("@username", MySqlDbType.VarChar);
            cmd.Parameters["@username"].Value = txtUsername.Text;

            try
            {
                conn.Open();
                reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    string saltAndPwd = String.Concat(txtPassword.Text, reader["salt"].ToString());
                    string hashSaltAndPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");

                    if (hashSaltAndPwd.Equals(reader["hashed_pw"].ToString()))
                    {
                        if (reader["activated"].ToString().Equals("Y"))
                        {
                            Session["Username"] = reader["username"].ToString();
                            Session["Role"] = reader["role"].ToString();
                            Session["UserID"] = reader["user_id"].ToString();
                            Session["EmailAddress"] = reader["email"].ToString();

                            if (reader["role"].ToString().Equals("0"))
                            {
                                Session["PermanentRole"] = "admin";
                            }
                            else if (reader["role"].ToString().Equals("2"))
                            {
                                Session["PermanentRole"] = "tutor";
                            }

                            Response.Redirect("~/portal.aspx");
                        }
                        else
                        {
                            lblError.Text = "Your account has not been activated.  Please check your inbox and activate your account or reset your password by clicking the link above.";
                        }
                    }
                    else
                    {
                        lblError.Text = "Incorrect password.";
                    }
                }
                else
                {
                    lblError.Text = "Username does not exist.";
                }

                reader.Close();
            }
            catch
            {
                lblError.Text = "Database connection error. Please try again.";
            }
            finally
            {
                conn.Close();
            }
        }
    }

最佳答案

1) conn.Close();没有必要,因为 using 语句将调用 close为你。它相当于

MySqlConnection conn = new MySqlConnection(connStr)
try
{
     ....
}
finally
{
    conn.Close();
}

2)形式的捕获
catch (Exception ex)
{
    throw ex;
}

在我能想到的任何情况下都不推荐。它有2个问题
  • 除了重新抛出异常之外,它什么也没做。除非你想对它做点什么(例如:记录错误),否则你不会捕捉到异常
  • 重新抛出异常 throw ex;削减堆栈跟踪。任何捕获该异常的人都会看到该行生成的错误,丢失有用的信息
  • 关于c# - ASP.Net C# - try-catch-finally 和 using 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25183536/

    相关文章:

    java - sql server 的等效 jdbc 连接字符串

    java - Try-Catch 选项在 Java 中不运行

    c# - using 子句中的隐式变量会被垃圾回收吗?

    Asp.net - Web.Config - 自定义错误

    c# - WCF:身份验证服务还是基于 token 的安全性?

    c# - 如何在 MVC3 中使用 @Viewbag 在 ASP.NET C# 中将值设置为 @Html.TextBox()

    R:Coeftest 导致错误

    json - 错误: The argument type 'int' can't be assigned to the parameter type 'String'

    c# - 在特定条件下从两个数据表中构建一个

    c# - 如何删除谷歌浏览器 cookie