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

时间:2015-04-09 20:24:08

标签: c#

如何达到以下要求:

  1. “检索”按钮点击事件:
    • 如果用户未在CustID中输入txtCustID,则需要通过lblMessage通知他们输入客户ID;
    • 如果输入CustId,则数据库中不存在通知用户它不存在lblMessage
  2. 更新按钮点击事件 - 需要确保数据库中已存在客户ID。
  3. 删除按钮单击事件:与“检索”按钮的要求相同。
  4. 我必须使用错误/异常处理(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 个答案:

答案 0 :(得分:1)

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

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

2)在.Net中抛出异常是很昂贵的。

3)如果应用程序的异常控制流如何将它们与实际异常区分开来(当某些东西没有按预期工作时抛出)?

另一方面,如果您希望在问题中列出的任何方案发生时抛出异常,那么您可以使用标准.Net 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块中的地方,尽管在您的问题中未提及。基本上,您与服务器连接的任何地方都可能导致意外情况(例如,服务器可能无法使用)。