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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. where to put try catch block!

where to put try catch block!

Scheduled Pinned Locked Moved C#
databasequestion
17 Posts 7 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.
  • H Hussam Fattahi

    hi a function called Save() saves user input to database should i write try catch block like this

    private void Save()
    {
    try
    {
    //My code goes here
    }
    catch (SqlException sqlEx)
    {
    MessageBox.Show(sqlEx.Message);
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }

    or should i write it like this in the function or event handler that calls Save();

    try
    {
    Save();
    }
    catch (SqlException sqlEx)
    {
    MessageBox.Show(sqlEx.Message);
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

    and what is the difference, if there was a difference and which is a better coding practice thanks

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #3

    If "Save" can throw (or cause) exceptions that you can handle locally, then surround the method with a catch-block. Don't accomodate for exceptions that you cannot recover from - a "catch Exception" will also catch a EOutOfMemory - a general error that would best be handled in the global exception handler. --edit-- I'm using the tooltips from intellisense to determine what exceptions to expect. Enter "System.IO.File.Re", and press <Ctrl>-<space>, and intellisense will pop up with the method ReadAllBytes. It also shows a tooltip, with a prototype of the method and a list of exceptions that the method can throw. If there's anything in the list that you can handle, then do so. All other things should be left to the errorhandler[^].

    I are Troll :suss:

    H 1 Reply Last reply
    0
    • H Hussam Fattahi

      hi a function called Save() saves user input to database should i write try catch block like this

      private void Save()
      {
      try
      {
      //My code goes here
      }
      catch (SqlException sqlEx)
      {
      MessageBox.Show(sqlEx.Message);
      }
      catch (Exception ex)
      {
      MessageBox.Show(ex.Message);
      }
      }

      or should i write it like this in the function or event handler that calls Save();

      try
      {
      Save();
      }
      catch (SqlException sqlEx)
      {
      MessageBox.Show(sqlEx.Message);
      }
      catch (Exception ex)
      {
      MessageBox.Show(ex.Message);
      }

      and what is the difference, if there was a difference and which is a better coding practice thanks

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #4

      The answer, of course, is it depends on many factors. In your first option the Save() method should take some action if it catches an exception and then return a status to its calling method to tell it whether the function succeeded or not. However, in the second sample the calling method is expected to understand an SQL exception, whereas it should really only be expected to handle "Save exceptions". So in this case sample one is probably the better choice.

      txtspeak is the realm of 9 year old children, not developers. Christian Graus

      H 1 Reply Last reply
      0
      • L Lost User

        The answer, of course, is it depends on many factors. In your first option the Save() method should take some action if it catches an exception and then return a status to its calling method to tell it whether the function succeeded or not. However, in the second sample the calling method is expected to understand an SQL exception, whereas it should really only be expected to handle "Save exceptions". So in this case sample one is probably the better choice.

        txtspeak is the realm of 9 year old children, not developers. Christian Graus

        H Offline
        H Offline
        Hussam Fattahi
        wrote on last edited by
        #5

        the problem is that many exceptions are expected and returning a bool value is not enought to descripe what error has been caught, so i need to handle in the function that calls save

        L 2 Replies Last reply
        0
        • D DaveyM69

          It depends on what you're going to do with the exception. If the exception is of no consequence to external code and can be handled within the Save method itself, then keep the try/catch in there. If the calling code may (now or in the future) want to do something depending on the exception then wrap the Save in the calling code. The second way is more flexible in the long term IMO. If you decide to use the first then it may be worth changing the Save to return a bool to indicate success or failure to the calling code so it still has the option of retrying the Save operation.

          Dave

          If this helped, please vote & accept answer!

          Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

          H Offline
          H Offline
          Hussam Fattahi
          wrote on last edited by
          #6

          DaveyM69 wrote:

          If the exception is of no consequence to external code

          my english is not very good, i don't get what you mean by this by the way i'm using llblgen

          D 1 Reply Last reply
          0
          • L Lost User

            If "Save" can throw (or cause) exceptions that you can handle locally, then surround the method with a catch-block. Don't accomodate for exceptions that you cannot recover from - a "catch Exception" will also catch a EOutOfMemory - a general error that would best be handled in the global exception handler. --edit-- I'm using the tooltips from intellisense to determine what exceptions to expect. Enter "System.IO.File.Re", and press <Ctrl>-<space>, and intellisense will pop up with the method ReadAllBytes. It also shows a tooltip, with a prototype of the method and a list of exceptions that the method can throw. If there's anything in the list that you can handle, then do so. All other things should be left to the errorhandler[^].

            I are Troll :suss:

            H Offline
            H Offline
            Hussam Fattahi
            wrote on last edited by
            #7

            thanks for reply

            1 Reply Last reply
            0
            • H Hussam Fattahi

              the problem is that many exceptions are expected and returning a bool value is not enought to descripe what error has been caught, so i need to handle in the function that calls save

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #8

              Hussam Fattahi wrote:

              i need to handle in the function that calls save

              That's fine, I was only offering suggestions based on your original post. It all comes down to knowing what your program is doing and how it needs to react to exceptions. Only you can really decide where is the best place, based on your understanding of the code.

              txtspeak is the realm of 9 year old children, not developers. Christian Graus

              H 1 Reply Last reply
              0
              • H Hussam Fattahi

                hi a function called Save() saves user input to database should i write try catch block like this

                private void Save()
                {
                try
                {
                //My code goes here
                }
                catch (SqlException sqlEx)
                {
                MessageBox.Show(sqlEx.Message);
                }
                catch (Exception ex)
                {
                MessageBox.Show(ex.Message);
                }
                }

                or should i write it like this in the function or event handler that calls Save();

                try
                {
                Save();
                }
                catch (SqlException sqlEx)
                {
                MessageBox.Show(sqlEx.Message);
                }
                catch (Exception ex)
                {
                MessageBox.Show(ex.Message);
                }

                and what is the difference, if there was a difference and which is a better coding practice thanks

                K Offline
                K Offline
                Keith Barrow
                wrote on last edited by
                #9

                You shouldn't do this:

                catch (Exception ex)
                {
                MessageBox.Show(ex.Message);
                }

                unless you have a very good reason (e.g. this is a top-level exception handler). It is considered bad practise, you should catch known exception types, the code you have will "hide" unexpected exceptions (from testing etc).

                Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter. Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                H 1 Reply Last reply
                0
                • L Lost User

                  Hussam Fattahi wrote:

                  i need to handle in the function that calls save

                  That's fine, I was only offering suggestions based on your original post. It all comes down to knowing what your program is doing and how it needs to react to exceptions. Only you can really decide where is the best place, based on your understanding of the code.

                  txtspeak is the realm of 9 year old children, not developers. Christian Graus

                  H Offline
                  H Offline
                  Hussam Fattahi
                  wrote on last edited by
                  #10

                  thanks, your help is greetly appreciated

                  1 Reply Last reply
                  0
                  • H Hussam Fattahi

                    DaveyM69 wrote:

                    If the exception is of no consequence to external code

                    my english is not very good, i don't get what you mean by this by the way i'm using llblgen

                    D Offline
                    D Offline
                    DaveyM69
                    wrote on last edited by
                    #11

                    I mean if the calling code will be able to continue regardless of specific exceptions then it's safe to catch these inside the save.

                    Dave

                    If this helped, please vote & accept answer!

                    Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
                    BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                    H 1 Reply Last reply
                    0
                    • K Keith Barrow

                      You shouldn't do this:

                      catch (Exception ex)
                      {
                      MessageBox.Show(ex.Message);
                      }

                      unless you have a very good reason (e.g. this is a top-level exception handler). It is considered bad practise, you should catch known exception types, the code you have will "hide" unexpected exceptions (from testing etc).

                      Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter. Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                      H Offline
                      H Offline
                      Hussam Fattahi
                      wrote on last edited by
                      #12

                      i thought exception hiding is doing like this

                      catch (Exception ex)
                      {

                      }

                      and i'm not sure what specific exception will happen so i used the general exception thanks

                      K 1 Reply Last reply
                      0
                      • H Hussam Fattahi

                        hi a function called Save() saves user input to database should i write try catch block like this

                        private void Save()
                        {
                        try
                        {
                        //My code goes here
                        }
                        catch (SqlException sqlEx)
                        {
                        MessageBox.Show(sqlEx.Message);
                        }
                        catch (Exception ex)
                        {
                        MessageBox.Show(ex.Message);
                        }
                        }

                        or should i write it like this in the function or event handler that calls Save();

                        try
                        {
                        Save();
                        }
                        catch (SqlException sqlEx)
                        {
                        MessageBox.Show(sqlEx.Message);
                        }
                        catch (Exception ex)
                        {
                        MessageBox.Show(ex.Message);
                        }

                        and what is the difference, if there was a difference and which is a better coding practice thanks

                        A Offline
                        A Offline
                        Abhinav S
                        wrote on last edited by
                        #13

                        An approach could be to put the SQLException within the Save() method and the general exception outside - that way SQLExceptions are caught in the Save method and anything else outside.

                        Me, I'm dishonest. And a dishonest man you can always trust to be dishonest.
                        Honestly. It's the honest ones you want to watch out for...

                        1 Reply Last reply
                        0
                        • D DaveyM69

                          I mean if the calling code will be able to continue regardless of specific exceptions then it's safe to catch these inside the save.

                          Dave

                          If this helped, please vote & accept answer!

                          Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
                          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                          H Offline
                          H Offline
                          Hussam Fattahi
                          wrote on last edited by
                          #14

                          thanks for clarification

                          1 Reply Last reply
                          0
                          • H Hussam Fattahi

                            the problem is that many exceptions are expected and returning a bool value is not enought to descripe what error has been caught, so i need to handle in the function that calls save

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #15

                            Hussam Fattahi wrote:

                            the problem is that many exceptions are expected and returning a bool value is not enought to descripe what error has been caught, so i need to handle in the function that calls save

                            There is (probably) more than one place where you "save" data. Some things can be handled locally; you might want to handle a "reconnect" to the database and execute the query again. That's the thing that you should catch. All other things should be allowed to pass by. You'd want two things to happen when an exception occurs; the user needs to know, and someone might be interested in the details of the exception later on. First things first, the user needs to be informed that something went wrong. That's where the general error-handler comes in, it's a special event that traps all unhandled exceptions. From there you can show a message - without a stacktrace, explaining what went wrong in layman-terms, and explaining what countermeasures can be taken. This way, the user gets a "Disk Full" message, without every programmer checking each method individually and displaying their own windows. It's quite easy to display a helpfull message for the most common ones and to redirect the user to a helpfull webpage. You'd probably want to log all the exceptions that you didn't handle; these should be treated as bugs. Log4Net could help you out there :)

                            I are Troll :suss:

                            1 Reply Last reply
                            0
                            • H Hussam Fattahi

                              i thought exception hiding is doing like this

                              catch (Exception ex)
                              {

                              }

                              and i'm not sure what specific exception will happen so i used the general exception thanks

                              K Offline
                              K Offline
                              Kevin McFarlane
                              wrote on last edited by
                              #16

                              Hussam Fattahi wrote:

                              i thought exception hiding is doing like this

                              Have a study of this: Design Guidelines for Exceptions[^]

                              Kevin

                              1 Reply Last reply
                              0
                              • H Hussam Fattahi

                                hi a function called Save() saves user input to database should i write try catch block like this

                                private void Save()
                                {
                                try
                                {
                                //My code goes here
                                }
                                catch (SqlException sqlEx)
                                {
                                MessageBox.Show(sqlEx.Message);
                                }
                                catch (Exception ex)
                                {
                                MessageBox.Show(ex.Message);
                                }
                                }

                                or should i write it like this in the function or event handler that calls Save();

                                try
                                {
                                Save();
                                }
                                catch (SqlException sqlEx)
                                {
                                MessageBox.Show(sqlEx.Message);
                                }
                                catch (Exception ex)
                                {
                                MessageBox.Show(ex.Message);
                                }

                                and what is the difference, if there was a difference and which is a better coding practice thanks

                                P Offline
                                P Offline
                                PIEBALDconsult
                                wrote on last edited by
                                #17

                                In the example given, the second way is probably better -- I wouldn't want to call your Save method from a Windows Service and have it try to pop up a message.

                                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