Search code examples
c#oledb

try-catch block not catching the Exception


I'm using a try-catch block to identify the lack of some data in a database. Before I started using the while to check user input it was doing fine but now the try-catch block wont be executed (the while is inside the try-catch). The exception I'm trying to catch is the InvalidOperationException thrown by the OleDbDataReader when the query returns nothing.

try
{
    string _cmd = "SELECT razao_social FROM tblImobiliarias WHERE cnpj ='" + ValorConsulta.Text + "'";
    string conn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\\\10.7.41.153\\Apoio\\Davi_Database\\Base_Imo.accdb";
    OleDbConnection Connection = new OleDbConnection(conn);
    OleDbCommand Command = new OleDbCommand(_cmd, Connection);
    Connection.Open();
    OleDbDataReader reader = Command.ExecuteReader();
    while (reader.Read())
    {
        int _resMatriz = 0;
        DialogResult result;
        result = MessageBox.Show(
              "Encontrado imobiliária: " 
            + reader[_resMatriz] 
            + ".\nEstá correto?", "Pesquisa", MessageBoxButtons.YesNo);
        _resMatriz++;
        if (result == System.Windows.Forms.DialogResult.Yes)
        {
            MessageBox.Show("CarregaImo()");
            break;
        }
        else
        {
            continue;
        } 
    }
}
catch (InvalidOperationException ex)
{
    MessageBox.Show(
        "O CNPJ " 
        + ValorConsulta.Text 
        + " não foi localizado no sistema.\nOs dados não podem ter pontuação. Tente novamente",
        "Pesquisa", 
        MessageBoxButtons.OK,
        MessageBoxIcon.Error);
    throw new InvalidOperationException();
}

Solution

  • I would advise against using an Exception for normal application logic. If your reader has no results, you can use the 'HasRows` property like so:

    OleDbDataReader reader = Command.ExecuteReader();
    if(reader.HasRows)
    {
        // Do what you need if there are rows
    }
    else // Instead of an exception handler
    {
        MessageBox.Show("O CNPJ " + ValorConsulta.Text + " não foi localizado no sistema.\nOs dados não podem ter pontuação. Tente novamente", "Pesquisa", MessageBoxButtons.OK, MessageBoxIcon.Error);
        throw new InvalidOperationException(); // If you must throw the exception
    }