c# - Trouble with a try and catch exception
问题描述
Working on a school project, i found an interesting code to make a input box for c# here. Im using it to make a find request in a DB. But i got a problem. when i close the message box with cancel or the close button, it execute the catch, while the catch is intended for a connexion problem. How i avoid that?
Edit : With some help i identified the reason of the exception. Input remains empty and cause the exception. How i check now if the message box was closed, to make a condition where i give a value in that case?
Here is the code of the "find" option:
private void TEACHER_BTN_find_Click(object sender, EventArgs e)
{
string input = "";
ShowInputDialog(ref input);
try
{
cnx.Open();
string req1 = "select nom_prof, pre_prof, ville_prof from Professeur where mat_prof ="+input;
cmd.CommandText = req1;
OleDbDataReader selection = cmd.ExecuteReader();
if (selection.Read())
{
TEACHER_TXB_reg.Text = input;
TEACHER_TXB_name.Text = selection[0].ToString();
TEACHER_TXB_lastn.Text = selection[1].ToString();
TEACHER_TXB_city.Text = selection[2].ToString();
}
else
MessageBox.Show("Matricule introuvable.");
cnx.Close();
}
catch
{
MessageBox.Show("Erreur de connexion.");
}
}
解决方案
您可以有多个catch
子句来捕获特定或一般异常。要捕获一般异常,您可以
catch (Exception ex)
{
//handle general exception here.
MessageBox.Show(ex.Message);
}
要捕获特定异常,在您的情况下是数据库异常,您可以
catch (DbException exDb)
{
//handle your db exception here. It will help you debug as well. You can
//log them somewhere for future reference.
}
希望能帮助到你 :)
推荐阅读
- python - 如何请求从 ipcam 获取图片?
- python - 如何根据条件替换数据框中的数据
- r - 查找 R 中的所有 uniq 组合
- r - 图例未显示在 R 图中
- reactjs - create-react-app 即插即用 Eslint 错误
- c# - C# 中的 JSON 序列化 - 对象中的对象
- java - 如何从哈希图中检索值,其中键是vaadin中的组合框项
- mongodb - Mongo领域功能。数组上的 $push 和其他上的 $set
- javascript - 添加 compilerOptions 后 VS Code 代码导航不起作用
- pandas - 无法导入所需的依赖项:numpy