c# - 在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);
}
解决方案
您正在捕捉、处理和抑制Exception
in ExecuteNonQueryF
:
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
虽然这Exception
通过显示消息来处理,但它会导致代码继续执行;Exception
不会向调用者提出。
如果您在执行throw
后添加,则将引发调用者并停止执行。MessageBox.Show
Exception
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
throw;
}
另一种选择是完全删除它try-catch
-ExecuteNonQueryF
让调用者(您的button
onclick
方法)处理Exception
.
推荐阅读
- ruby-on-rails - 导入 ruby c 扩展时找不到 .so 文件。(在窗户上)
- html - 渐变背景正在切断 png 图像
- tree-traversal - 以下二叉搜索树的预排序结果
- class - 在颤动中打印整数类型的类项
- ios - 在文本字段中插入任何内容后,UITextfield 的位置发生了变化
- asp.net-mvc - 如何解决这个问题?不支持关键字:“元数据”
- sql - 在 Oracle SQL 中使用 group 和 listagg 跨列和行连接
- python - lxml中的iterdescendants()和iterchildren()有什么区别?
- rust - 如何定义嵌套级别未知的嵌套 HashMap?
- android-permissions - 在不启动意图的情况下授予对多个文件的读取权限