Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Try catch finally

Try catch finally

Scheduled Pinned Locked Moved C#
databasehelpquestion
5 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    Claudiu Schiopu
    wrote on last edited by
    #1

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

    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 :) Thank you!

    OriginalGriffO 1 Reply Last reply
    0
    • C Claudiu Schiopu

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

      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 :) Thank you!

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      The whole idea of try...catch blocks is to do exactly what you have done: catch an error, report it (or log it, or fix it) and let the software continue without crashing. In your case, the exception is being thrown because the result returned by SQL is not an integer, and cannot be cast to an integer (it may be a DBNull, or a string for example - either put a breakpoint on the ExecuteScalar line and look at the return, or include the return value in your message to actually fix the problem). But the insert has been done by that time, so the row is in the DB already.

      If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      C 1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        The whole idea of try...catch blocks is to do exactly what you have done: catch an error, report it (or log it, or fix it) and let the software continue without crashing. In your case, the exception is being thrown because the result returned by SQL is not an integer, and cannot be cast to an integer (it may be a DBNull, or a string for example - either put a breakpoint on the ExecuteScalar line and look at the return, or include the return value in your message to actually fix the problem). But the insert has been done by that time, so the row is in the DB already.

        If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.

        C Offline
        C Offline
        Claudiu Schiopu
        wrote on last edited by
        #3

        Thank you for your message! Beceause now i try to learn some C# programming (and write in english), your message help me to understand about Try catch. Just to be sure that i have understand: 1. I have my btnSave code that look like this:

        protected void btnSave_Click(object sender, EventArgs e)
        {
        try
        {
        int x = 0; //this will be the ID of the new inserted record
        x = SaveData();
        if (x > 0)
        {
        lblMesaje.Text = " Your new ID is: " + x.ToString();
        }
        }
        catch (Exception ex)
        {
        lblMesage.Text = "Some error occured: " + ex.Message;
        }

           }
        

        2. Now here is my Insert function:

        private int SaveData()
        {
        //SQL objects set..

                int result= 0;
                try
                {
                    if (sqlconn.State != ConnectionState.Open)
                    {
                        sqlconn.Open();
                    }
                    result= Convert.ToInt32(cmd.ExecuteScalar());
                    return result;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    if (sqlconn.State != ConnectionState.Closed)
                    {
                        sqlconn.Close();
                    }
                }
                
            }
        

        Now i throw and exception in SaveData function and the message is displayed to the user. Is ok? Thanks again!

        OriginalGriffO D 2 Replies Last reply
        0
        • C Claudiu Schiopu

          Thank you for your message! Beceause now i try to learn some C# programming (and write in english), your message help me to understand about Try catch. Just to be sure that i have understand: 1. I have my btnSave code that look like this:

          protected void btnSave_Click(object sender, EventArgs e)
          {
          try
          {
          int x = 0; //this will be the ID of the new inserted record
          x = SaveData();
          if (x > 0)
          {
          lblMesaje.Text = " Your new ID is: " + x.ToString();
          }
          }
          catch (Exception ex)
          {
          lblMesage.Text = "Some error occured: " + ex.Message;
          }

             }
          

          2. Now here is my Insert function:

          private int SaveData()
          {
          //SQL objects set..

                  int result= 0;
                  try
                  {
                      if (sqlconn.State != ConnectionState.Open)
                      {
                          sqlconn.Open();
                      }
                      result= Convert.ToInt32(cmd.ExecuteScalar());
                      return result;
                  }
                  catch (Exception)
                  {
                      throw;
                  }
                  finally
                  {
                      if (sqlconn.State != ConnectionState.Closed)
                      {
                          sqlconn.Close();
                      }
                  }
                  
              }
          

          Now i throw and exception in SaveData function and the message is displayed to the user. Is ok? Thanks again!

          OriginalGriffO Offline
          OriginalGriffO Offline
          OriginalGriff
          wrote on last edited by
          #4

          :thumbsup: Looks good!

          If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

          1 Reply Last reply
          0
          • C Claudiu Schiopu

            Thank you for your message! Beceause now i try to learn some C# programming (and write in english), your message help me to understand about Try catch. Just to be sure that i have understand: 1. I have my btnSave code that look like this:

            protected void btnSave_Click(object sender, EventArgs e)
            {
            try
            {
            int x = 0; //this will be the ID of the new inserted record
            x = SaveData();
            if (x > 0)
            {
            lblMesaje.Text = " Your new ID is: " + x.ToString();
            }
            }
            catch (Exception ex)
            {
            lblMesage.Text = "Some error occured: " + ex.Message;
            }

               }
            

            2. Now here is my Insert function:

            private int SaveData()
            {
            //SQL objects set..

                    int result= 0;
                    try
                    {
                        if (sqlconn.State != ConnectionState.Open)
                        {
                            sqlconn.Open();
                        }
                        result= Convert.ToInt32(cmd.ExecuteScalar());
                        return result;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        if (sqlconn.State != ConnectionState.Closed)
                        {
                            sqlconn.Close();
                        }
                    }
                    
                }
            

            Now i throw and exception in SaveData function and the message is displayed to the user. Is ok? Thanks again!

            D Offline
            D Offline
            dybs
            wrote on last edited by
            #5

            This is fine, although the

            Claudiu Schiopu wrote:

            catch (Exception) { throw; }

            doesn't really do much. You can just have the

            try

            and

            finally

            blocks, and the code would effectively do the same thing.

            The shout of progress is not "Eureka!" it's "Strange... that's not what i expected". - peterchen

            1 Reply Last reply
            0
            Reply
            • Reply as topic
            Log in to reply
            • Oldest to Newest
            • Newest to Oldest
            • Most Votes


            • Login

            • Don't have an account? Register

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • World
            • Users
            • Groups