如何在不退出循环的情况下处理异常

本文关键字:情况下 处理 异常 循环 退出 | 更新日期: 2023-09-27 18:36:09

我有以下问题:

我尝试插入multiple employee data,但是员工数据应该只插入一次,但是如果我选择多个员工并且之前已经插入了其中一个,根据数据库约束会抛出错误怎么办。

我的

问题是(最佳实践):如何处理此异常,我想恢复插入不重复的员工而不退出我的循环,因为该异常.


protected void ibtn_save_detail_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                Fill_Form();
                RewardDetails obj = new RewardDetails();
                var collection = ddl_employees.CheckedItems;
                for (int i = 0; i < collection.Count; i++)
                {
                    obj.Emp_num = int.Parse(collection[i].Value);
                    obj.Req_ser = int.Parse(reqSer);
                    obj.Req_year = int.Parse(reqYear);
                    DataTable dt = Utilities.GetDep(obj.Emp_num);
                    obj.Main_code = int.Parse(dt.Rows[0]["dep_code"].ToString());
                    obj.Year = int.Parse(dt.Rows[0]["dep_year"].ToString());
                    obj.Dep_name = dt.Rows[0]["dep_name"].ToString();
                    string res = obj.InsertReward();//exception in case of repetition .
                    if (!string.IsNullOrEmpty(res))
                    {
                        div_detail_result.Visible = true;
                        SetMessage("");
                    }
                    else
                    {
                        SetMessage("Adding the employee has been done :" + collection[i].Text.Trim());
                    }
                }
                BindDetailsGV(obj.Req_ser, obj.Req_year);
                ddl_employees.ClearCheckedItems();
            }
            catch (Exception ee)
            {
                SetMessage("Error,this employee has been added before.");
                ddl_employees.ClearCheckedItems();
            }
        }

如何在不退出循环的情况下处理异常

移动您的 try/catch 以仅应用于obj.InsertReward();行。另外,不要抓住Exception,只是insertReward抛出的特定异常。

因此,代码最终可能会如下所示:

protected void ibtn_save_detail_Click(object sender, ImageClickEventArgs e)
{
    Fill_Form();
    RewardDetails obj = new RewardDetails();
    var collection = ddl_employees.CheckedItems;
    for (int i = 0; i < collection.Count; i++)
    {
        obj.Emp_num = int.Parse(collection[i].Value);
        ...
        string res;
        try
        {
            res = obj.InsertReward();
            // stuff to do if added
        }
        catch (RewardExistsException)
        {
            // stuff to do if already exists
        }
    }
}

你应该把try放在循环中:

for (int i = 0; i < collection.Count; i++)
{
    try
            {
                obj.Emp_num = int.Parse(collection[i].Value);
                obj.Req_ser = int.Parse(reqSer);
                obj.Req_year = int.Parse(reqYear);
                DataTable dt = Utilities.GetDep(obj.Emp_num);
                obj.Main_code = int.Parse(dt.Rows[0]["dep_code"].ToString());
                obj.Year = int.Parse(dt.Rows[0]["dep_year"].ToString());
                obj.Dep_name = dt.Rows[0]["dep_name"].ToString();
                string res = obj.InsertReward();//exception in case of repetition .
                if (!string.IsNullOrEmpty(res))
                {
                    div_detail_result.Visible = true;
                    SetMessage("");
                }
                else
                {
                    SetMessage("Adding the employee has been done :" + collection[i].Text.Trim());
                }
            }
    catch (Exception ee)
        {
            // your exception code
        }
}
try{
string res = obj.InsertReward();
}
catch(Exception ex){
    continue; // or rethrow exception in some condions
}

并且不要忘记在填写 obj 时可能会出现异常

请确保您的 try catch 不会封装 for 循环所以:

try
{
   for(...){}
}
catch(Exception){  }

应该是:

for(...)
{
    try{  }
    Catch{  }
}

或者,如果异常未在 for 循环中抛出,只需在启动循环之前捕获或在启动循环后尝试。