Frage

Maby this is simple for you, but for me is not. I have this code:

Private int InsertData()
{ 
  int rezultat = 0;
       try
       {
           if (sqlconn.State != ConnectionState.Open)
           {
               sqlconn.Open();
           }
           rezultat = (int)cmd.ExecuteScalar();

       }
       catch (Exception ex)
       {
           lblMesaje.Text = "Eroare: " + ex.Message.ToString();

       }
       finally
       {
           if (sqlconn.State != ConnectionState.Closed)
           {
               sqlconn.Close();
           }
       }

       return rezultat;
}

Is just for inserting a new record in a table. Even if this throw an error "Specified cast is not valid." "rezultat=(int)cmd.ExecuteScalar();" - the code is executed and the row is inserted in the database, and the execution continues.

Why it continues? Maby i don't understand the try catch finally yet Smile | :)

Thank you!

War es hilfreich?

Lösung

In your code you explicitly catch Exception. That why the execution continue. If you want stop the execution if any exception is catched so you need to throw an exception. Throw new Exception(ex.getMessage());

But it's not the best practice. Try to catch only declared exceptions, not the high level Exception class.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top