错误/异常处理(try-catch)C#



如何实现以下要求:

  1. 检索按钮点击事件:
    • 如果用户未在CCD_ 2中输入CCD_ 1,则需要通知用户通过CCD_
    • 如果输入的CCD_ 4不存在于数据库中,则通过CCD_
  2. 更新按钮点击事件-需要确保数据库中已经存在客户ID
  3. 删除按钮点击事件:与检索按钮的要求相同

我必须使用错误/异常处理(try-catch)来实现这些(项目要求)。我花了几个小时尝试,但没有成功。如果能得到帮助,我将不胜感激!我的代码如下:

namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
    SqlConnection conn;
    SqlDataAdapter adapter = new SqlDataAdapter();
    DataTable table = new DataTable();
    SqlCommand command = new SqlCommand();
    protected void Page_Load(object sender, EventArgs e)
    {
        conn = new SqlConnection(ConfigurationManager.
        ConnectionStrings["dbConnection1"].ConnectionString);       
    }
    private void Page_PreInit(object sender, EventArgs e)
    {
        HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
        if (setTheme != null)
        {
            Page.Theme = setTheme.Value;
        }
    }
    protected void Clear()
    {
        txtCustID.Text = "";
        txtFirstname.Text = "";
        txtSurname.Text = "";
        rbtGender.SelectedValue = "";
        txtAge.Text = "";
        txtAddress1.Text = "";
        txtAddress2.Text = "";
        txtCity.Text = "";
        txtPhone.Text = "";
        txtMobile.Text = "";
        txtEmail.Text = "";
        txtEmail2.Text = "";
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        SqlDataAdapter adapter1 = new SqlDataAdapter();
        DataTable table1 = new DataTable();
        SqlCommand command1 = new SqlCommand();
        Clear();
        conn = new SqlConnection(ConfigurationManager.
        ConnectionStrings["dbConnection1"].ConnectionString);
        command1.Connection = conn;
        command1.CommandType = CommandType.StoredProcedure;
        command1.CommandText = "LargestCustID";
        command1.Connection.Open();
        int id = (int)command1.ExecuteScalar() + 1;
        txtCustID.Text = id.ToString();
        command1.Dispose();
        conn.Close();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        conn = new SqlConnection(ConfigurationManager.
        ConnectionStrings["dbConnection1"].ConnectionString);
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "AddCustomer";
        command.Connection.Open();
        command.Parameters.AddWithValue("@CustID",      
         int.Parse(txtCustID.Text));
        command.Parameters.AddWithValue("@Firstname", txtFirstname.Text);
        command.Parameters.AddWithValue("@Surname", txtSurname.Text);
        command.Parameters.AddWithValue("@Gender", rbtGender.SelectedValue);
        command.Parameters.AddWithValue("@Age", int.Parse(txtAge.Text));
        command.Parameters.AddWithValue("@Address1", txtAddress1.Text);
        command.Parameters.AddWithValue("@Address2", txtAddress2.Text);
        command.Parameters.AddWithValue("@City", txtCity.Text);
        command.Parameters.AddWithValue("@Phone", txtPhone.Text);
        command.Parameters.AddWithValue("@Mobile", txtMobile.Text);
        command.Parameters.AddWithValue("@Email", txtEmail.Text);
        adapter.InsertCommand = command;
        adapter.InsertCommand.ExecuteNonQuery();
        lblMessage.Text = "The new record has been added to the database!";
        command.Connection.Close();
        Clear();
    }
    protected void btnRetrieve_Click(object sender, EventArgs e)
    {
        conn = new SqlConnection(ConfigurationManager.
        ConnectionStrings["dbConnection1"].ConnectionString);

        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "GetCustID";
        command.Connection.Open();
        SqlParameter param = new SqlParameter();
        param.ParameterName = "@CustID";
        param.SqlDbType = SqlDbType.Int;
        param.Direction = ParameterDirection.Input;
        param.Value = int.Parse(txtCustID.Text);
        command.Parameters.Add(param);
        adapter.SelectCommand = command;
        adapter.Fill(table);
        int id = table.Rows.Count;
        if (id == 0)
        {
            lblMessage.Text = "Customer ID does not exists!";
        } 
        else
        {
            lblMessage.Text = "";
            txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
            txtFirstname.DataBind();
            txtSurname.Text = table.Rows[0].Field<string>("Surname");
            txtSurname.DataBind();
            txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
            txtAge.DataBind();
            txtAddress1.Text = table.Rows[0].Field<string>("Address1");
            txtAddress1.DataBind();
            txtAddress2.Text = table.Rows[0].Field<string>("Address2");
            txtAddress2.DataBind();
            txtCity.Text = table.Rows[0].Field<string>("City");
            txtCity.DataBind();
            txtPhone.Text = table.Rows[0].Field<string>("Phone");
            txtPhone.DataBind();
            txtMobile.Text = table.Rows[0].Field<string>("Mobile");
            txtMobile.DataBind();
            txtEmail.Text = table.Rows[0].Field<string>("Email");
            txtEmail.DataBind();
        }   
        command.Connection.Close();
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        conn = new SqlConnection(ConfigurationManager.
        ConnectionStrings["dbConnection1"].ConnectionString);
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "UpdateCustomer";
        command.Connection.Open();
        command.Parameters.AddWithValue("@CustID", 
          int.Parse(txtCustID.Text));
        command.Parameters.AddWithValue("@Firstname", txtFirstname.Text);
        command.Parameters.AddWithValue("@Surname", txtSurname.Text);
        command.Parameters.AddWithValue("@Gender", rbtGender.SelectedValue);
        command.Parameters.AddWithValue("@Age", int.Parse(txtAge.Text));
        command.Parameters.AddWithValue("@Address1", txtAddress1.Text);
        command.Parameters.AddWithValue("@Address2", txtAddress2.Text);
        command.Parameters.AddWithValue("@City", txtCity.Text);
        command.Parameters.AddWithValue("@Phone", txtPhone.Text);
        command.Parameters.AddWithValue("@Mobile", txtMobile.Text);
        command.Parameters.AddWithValue("@Email", txtEmail.Text);
        lblMessage.Text = "The record has been updated!";
        command.Connection.Close();
        Clear();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            conn = new SqlConnection(ConfigurationManager.
            ConnectionStrings["dbConnection1"].ConnectionString);
            SqlCommand command = new SqlCommand();
            command.Connection = conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "DeleteCustomer";
            command.Connection.Open();

            SqlParameter param = new SqlParameter();
            param.ParameterName = "@CustID";
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            param.Value = int.Parse(txtCustID.Text);
            command.Parameters.Add(param);
            adapter.DeleteCommand = command;
            adapter.DeleteCommand.ExecuteNonQuery();
            int id = (int)param.Value;
            command.Connection.Close();
        }
        catch (Exception ex)
        {
            lblMessage.Text += "Please enter Customer ID!";
        }
        try
        {
            lblMessage.Text = "";
            SqlParameter param = new SqlParameter();
            param.ParameterName = "@CustID";
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            param.Value = int.Parse(txtCustID.Text);
            command.Parameters.Add(param);
            adapter.DeleteCommand = command;
            adapter.DeleteCommand.ExecuteNonQuery();
            int id = table.Rows.Count;
            id = (int)param.Value;
            lblMessage.Text += "Customer record has been deleted";
            command.Connection.Close();
         }
         catch (Exception ex)
         {
            lblMessage.Text = "Customer ID doesnot exists!";
         } 

        Clear();
    }

    public string CustID { get; set; }
}
}

听起来您正试图通过使用异常来控制应用程序的流。反对这种方法的原因有很多:

1) 代码很难理解和调试。

2) 正在中引发异常。网络是昂贵的。

3) 如果应用程序的异常控制流,您如何将它们与真正的异常(当某些事情不能按预期工作时抛出)区分开来?

另一方面,如果您想在问题中列出的任何场景发生时抛出异常,则可以使用标准。净Exception类:

if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
    throw new Exception("Id not provided.");
}

或者,您可以创建一个自定义异常来提供一些更具体的信息:

public class IdNotProvidedException : Exception
{
    public string MyCommandName { get; set; }
    public IdNotProvidedException(string msg)
        : base(msg)
    {
    }
    public IdNotProvidedException(string msg, string myCommandName)
        : base(msg)
    {
        this.MyCommandName = myCommandName;
    }
}

然后初始化并抛出自定义异常。

最后,虽然问题中没有提到,但代码中已经有一些地方值得封装在try...catch块中。基本上,与服务器连接的任何地方都可能导致意外情况(例如,服务器可能不可用)。

最新更新