首页 > 解决方案 > 在c#中向调用者方法发送异常

问题描述

大家好,我正在处理数据库分配,我有一个 Windows 窗体和一个类,用于连接数据库并执行查询和非查询。

问题:我正在使用 Post-Message 标签,它仅在“产品添加成功”时通知。但是当我发送错误数据时,可能会在数据库类的 executeNonQuery() 中发生异常,并且在捕获此异常并在消息框中显示错误之后。控制回到调用者,它在两种情况下都打印 lblPostMsg,即“产品已成功添加”。我希望当数据库类中发生异常时,我可以停止执行其余代码,或者如果调用方法中的异常可以被调用者方法捕获。

下面是windows窗体按钮的代码

 private void btnInsert_Click(object sender, EventArgs e)
    {
            con = new DbConnection();
            con.SqlQuery("INSERT INTO products VALUES(@products_ID,@products_Name)"); 
            con.cmd.Parameters.AddWithValue("@products_ID", txtProID.Text);
            con.cmd.Parameters.AddWithValue("@products_Name", txtProName.Text);
            try
            {
                con.ExecuteNonQueryF();

                this.categoriesTableAdapter1.Fill(this.purchasemasterDS.categories);
                SystemSounds.Beep.Play();
                lblPostMsg.Show();
                lblPostMsg.Text = "Product has been added successfully";

            }
            catch (Exception ex)
            {
                throw;
            }

            finally
            {
                con.CloseCon();
            }
    }

此代码来自 dbclass

public void ExecuteNonQueryF()
    {
        try
        {
            _con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (System.Exception ex)
        {

            MessageBox.Show("Exception " + ex);

        }

标签: c#sqlwinforms

解决方案


您正在捕捉、处理和抑制Exceptionin ExecuteNonQueryF

catch (System.Exception ex)
{    
    MessageBox.Show("Exception " + ex);    
}

虽然这Exception通过显示消息来处理,但它会导致代码继续执行;Exception不会向调用者提出。

如果您在执行throw后添加,则将引发调用者并停止执行。MessageBox.ShowException

catch (System.Exception ex)
{
    MessageBox.Show("Exception " + ex);
    throw;
}

另一种选择是完全删除它try-catch-ExecuteNonQueryF 让调用者(您的button onclick方法)处理Exception.


推荐阅读