首页 > 解决方案 > 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.");
    }
}

标签: c#

解决方案


您可以有多个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.
}

希望能帮助到你 :)


推荐阅读