2017-11-14 6 views
-3

try-catch 블록을 사용하여 데이터베이스의 일부 데이터가 없음을 식별합니다. 내가 사용자 입력을 확인하기 위해 잠시 사용하기 전에 잘하고 있었지만 이제는 try-catch 블록이 실행되지 않습니다 (while은 try-catch 안에 있습니다). 내가 잡으려고하는 예외는 쿼리가 아무것도 반환하지 않을 때 OleDbDataReader에 의해 throw되는 InvalidOperationException입니다.try-catch 블록이 예외를 catch하지 않습니다.

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(); 
} 
+5

그렇게하지 마십시오. 실제로 예외를 처리 할 수있는 경우에만 catch 블록을 가져야합니다. 최소한 "throw;"를 사용하십시오. – SLaks

+1

코드 시작 부분에 중단 점을 넣습니다. 프로그램을 실행하십시오. 코드를 한 줄씩 F10과 함께 실행합니다. 표시되는 모든 변수 위로 마우스를 이동하거나보기 윈도우에서 값을 봅니다. 이렇게하면 문제의 원인을 찾을 수 있습니다. –

+1

답이 아닙니다 : SQL 인젝션 공격에 취약하기 때문에 그런 식으로 쿼리를 작성하는 것을 권장합니다. 문자열 연결 대신 매개 변수를 사용하도록 변경하는 것이 좋습니다. – Fabulous

답변

0

일반적인 응용 프로그램 논리에 대해서는 Exception을 사용하지 않는 것이 좋습니다. 독자가 결과가 없다면 'HasRows` 속성을 다음과 같이 사용할 수 있습니다.

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 
}