-1

in the following code, if cmd1 and cmd2 passed with cmd3 failing. do c# abort all block (try block) ?, or continue executing cmd1 and cmd2 ?.

              try
            {

                sqlConnection1.Open();
                cmd1.ExecuteNonQuery();
                cmd2.ExecuteNonQuery();
                cmd3.ExecuteNonQuery();

            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured " + ex.Message);
            }

            finally
                {
                    sqlConnection1.Close();
                }
ellak
  • 2,531
  • 20
  • 26

4 Answers4

1

cmd1 and cmd2 would execute in the scenario you specify and the exception on cmd3 would be caught by the exception handling.

To achieve the behavior of aborting cmd1 and cmd2 if cmd3 fails, you would put all of the sql commands in a single stored procedure and use a TRANSACTION and ROLLBACK

Tanner
  • 22,205
  • 9
  • 65
  • 83
0

given your scenario cmd1 and cmd2 will execute and if there is execption then it will go to catch block. If cmd1 fails then it wont execute cmd2 and cmd3 and will go to catch block. Also it is worth reading this link here

Community
  • 1
  • 1
DevelopmentIsMyPassion
  • 3,541
  • 4
  • 34
  • 60
0

cmd1 and cmd2 will have been executed as try/catch blocks do not automatically perform transactions on queries. However you could perhaps use a transaction scope to perform a rollback and undo the changes made in cmd1/cmd2 if cmd3 fails.

Kyri Elia
  • 997
  • 9
  • 18
0

When an exception is thrown the code stop jumps to the nearst catch block.

any code below the point where the exception happened - is not executed.

In your senario perhaps you want to consider using TransactionScope like this:

using(var trans = new TransactionScope())
{
  try
  {
     //your setup code goes here

    sqlConnection1.Open();
                cmd1.ExecuteNonQuery();
                cmd2.ExecuteNonQuery();
                cmd3.ExecuteNonQuery();

    trans.Complete();
   }
   catch(Exception)
   {
    //handle exception
   }
}

Any changes made to the database are rolled back if the statemenet trans.Complete() is not executed.

Jens Kloster
  • 11,099
  • 5
  • 40
  • 54