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. Is try - catch block advisable?

Is try - catch block advisable?

Scheduled Pinned Locked Moved C#
questiondiscussion
34 Posts 11 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.
  • S Srinivas Kalabarigi

    I dont have a habit of using try-cahtch block unless i am sure it throws an exception... is it advisable to use it in most places of your code.... what is the best practice?

    Srinivas K

    J Offline
    J Offline
    jschell
    wrote on last edited by
    #14

    I catch everything on layer boundaries. What happens there depends on the layer and where I catch it. I catch everything on adapter boundaries, although that is just a specialization of a layer boundary. However I also tend to catch everything at the adapter top level as well. When I catch everything then handling involves the following 1. log it, and take appropriate action which might include throwing a different exception WITHOUT including the original exception. 2. Don't log it and take appropriate action which might include throwing a different exception INCLUDING the original exception in the new exception. I do NOT use catch alls which do nothing but log and then rethrow. That is pointless and a waste of time since the caller should be catching and will then end up logging as well. There are of course extreme conditions where the above can be problematic. For example out of memory errors. Those can cause the log to fail as well. However without some logging figuring out an out of memory occurred is impossible. There are things like stack over flow in C# which CANNOT be caught so one is kind of out luck there. This however does NOT mean that one can ignore the code that one is working with. If I am working on a communications layer then I expect communication exceptions. And I expect to take specific actions with regards to those. I suppose what it really comes down to is that I use catch all because I am almost certain that some unexpected exception will occur at some point and I need to still behave in some reasonable manner. At other times I am not certain and thus it is inappropriate to take such action. Which is why boundary layers are often the only place this occurs.

    1 Reply Last reply
    0
    • S Srinivas Kalabarigi

      I dont have a habit of using try-cahtch block unless i am sure it throws an exception... is it advisable to use it in most places of your code.... what is the best practice?

      Srinivas K

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

      Srinivas Kalabarigi wrote:

      i am sure it throws an exception

      That's silly; how do you do that?

      Srinivas Kalabarigi wrote:

      use it in most places of your code

      No, only where it makes sense.

      Srinivas Kalabarigi wrote:

      what is the best practice

      That depends on your situation; different domains require different techniques. I work mostly in the back-end with libraries and databases, which is very different from the front-end. Most times I have a catch, it's a catch-all; I rarely need to have special handling for different Exceptions. The main thing I usually need to do is to add information to the Data collection of the Exception and rethrow it. Many times, I also need to rollback a transaction or perform some other clean up task. Also, most times that a problem happens in a database all I get is a System.Data.DataException and I have to investigate it to see what the problem was -- deadlock, timeout, duplicate key, etc. (and no two database systems report it the same way) -- then I can wrap the DataException in a more detailed custom Exception -- DeadlockException, TimeoutException, DuplicateException, etc. and throw it so the caller can decide how to procede. The main thing here is to add information to make the caller's job easier; but the ultimate decision of what to do is up to the caller.

      1 Reply Last reply
      0
      • S Srinivas Kalabarigi

        I dont have a habit of using try-cahtch block unless i am sure it throws an exception... is it advisable to use it in most places of your code.... what is the best practice?

        Srinivas K

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

        Use try-catch unless you want your clients complaining "i got this error and then the entire application shut down".

        Apps - Color Analyzer | Arctic | XKCD | Sound Meter | Speed Dial

        L OriginalGriffO 2 Replies Last reply
        0
        • L Lost User

          Forbiddenx wrote:

          catch just about all exceptions

          Not using a try-catch construction; there's an event that's raised for unhandled exceptions; that's the place where one would log them.

          Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

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

          Eddy Vluggen wrote:

          that's the place where one would log them.

          But only at the top-most layer.

          1 Reply Last reply
          0
          • J jschell

            Forbiddenx wrote:

            If Website, catch just about all exceptions and store them into a database fo

            And what happens when the database throws an exception?

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

            That hardly ever happens. :rolleyes:

            1 Reply Last reply
            0
            • E Ennis Ray Lynch Jr

              I am going to compound a little on Eddy's Don't catch what you can't handle Don't throw what you can catch Expected exceptions are not exceptions test first, your code will be more rigorous.

              Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost "All users always want Excel" --Ennis Lynch

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

              Ennis Ray Lynch, Jr. wrote:

              Don't throw what you can catch

              Unless you are a value-added re-thrower.

              1 Reply Last reply
              0
              • A Abhinav S

                Use try-catch unless you want your clients complaining "i got this error and then the entire application shut down".

                Apps - Color Analyzer | Arctic | XKCD | Sound Meter | Speed Dial

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

                I'd rather have them complain once and explain that it's a bug that will never resurface, than having a lot of exceptions (and invalid states) that I don't know of. I love the PHP-approach; either do or die, don't fake it.

                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                OriginalGriffO J 2 Replies Last reply
                0
                • L Lost User

                  I'd rather have them complain once and explain that it's a bug that will never resurface, than having a lot of exceptions (and invalid states) that I don't know of. I love the PHP-approach; either do or die, don't fake it.

                  Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

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

                  I'm with Abhinav - use try catch, but report a problem to the user. Nothing, but nothing, is so damn annoying as losing an hour's work because a programmer didn't bother to allow for an alpha character in a numeric field! Have you never sworn because an app went "...caused an exception and needs to close" and you lose a bunch of work?

                  This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

                  "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

                  L 1 Reply Last reply
                  0
                  • A Abhinav S

                    Use try-catch unless you want your clients complaining "i got this error and then the entire application shut down".

                    Apps - Color Analyzer | Arctic | XKCD | Sound Meter | Speed Dial

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

                    Down vote countered - not checking or catching errors is just lazy programming, and is unfair on the people who pay our wages! :laugh:

                    This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

                    "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

                    A L 2 Replies Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      Down vote countered - not checking or catching errors is just lazy programming, and is unfair on the people who pay our wages! :laugh:

                      This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

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

                      OriginalGriff wrote:

                      Down vote countered

                      Thanks.

                      Apps - Color Analyzer | Arctic | XKCD | Sound Meter | Speed Dial

                      1 Reply Last reply
                      0
                      • OriginalGriffO OriginalGriff

                        I'm with Abhinav - use try catch, but report a problem to the user. Nothing, but nothing, is so damn annoying as losing an hour's work because a programmer didn't bother to allow for an alpha character in a numeric field! Have you never sworn because an app went "...caused an exception and needs to close" and you lose a bunch of work?

                        This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

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

                        OriginalGriff wrote:

                        Nothing, but nothing, is so damn annoying as losing an hour's work because a programmer didn't bother to allow for an alpha character in a numeric field!

                        Yes, it's loosing a day because that exception is swallowed somewhere deeply within the system.

                        OriginalGriff wrote:

                        Have you never sworn because an app went "...caused an exception and needs to close" and you lose a bunch of work?

                        There's an auto-save, but my Ctrl-S reflex is still alive. And yes, I'd rather see my app die, than pretend nothing happened (and have it continue with corrupted data that gets saved later)

                        Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                        OriginalGriffO 1 Reply Last reply
                        0
                        • OriginalGriffO OriginalGriff

                          Down vote countered - not checking or catching errors is just lazy programming, and is unfair on the people who pay our wages! :laugh:

                          This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

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

                          OriginalGriff wrote:

                          not checking or catching errors is just lazy programming

                          No-one advocates "not" checking them; so the statement that one should is superfluous. Using a pokemon-handler is lazy; if you expect an exception, than you can see if you can handle it locally. Unhandled exceptions would be logged in a single place.

                          Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                          OriginalGriffO 1 Reply Last reply
                          0
                          • L Lost User

                            OriginalGriff wrote:

                            Nothing, but nothing, is so damn annoying as losing an hour's work because a programmer didn't bother to allow for an alpha character in a numeric field!

                            Yes, it's loosing a day because that exception is swallowed somewhere deeply within the system.

                            OriginalGriff wrote:

                            Have you never sworn because an app went "...caused an exception and needs to close" and you lose a bunch of work?

                            There's an auto-save, but my Ctrl-S reflex is still alive. And yes, I'd rather see my app die, than pretend nothing happened (and have it continue with corrupted data that gets saved later)

                            Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

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

                            I'm not saying "swallow it" and "pretend nothing happened". I'm saying use the tools and locate it while you (as a programmer) can still prevent it adversely affecting the user. Then report it, log it (both is good) and give them a chance to do something. Just letting your program crash is just being lazy! :laugh:

                            This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

                            "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

                            L 1 Reply Last reply
                            0
                            • L Lost User

                              OriginalGriff wrote:

                              not checking or catching errors is just lazy programming

                              No-one advocates "not" checking them; so the statement that one should is superfluous. Using a pokemon-handler is lazy; if you expect an exception, than you can see if you can handle it locally. Unhandled exceptions would be logged in a single place.

                              Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

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

                              Eddy Vluggen wrote:

                              No-one advocates "not" checking them;

                              Um.

                              Eddy Vluggen wrote:

                              And yes, I'd rather see my app die, than pretend nothing happened (and have it continue with corrupted data that gets saved later)

                              Eddy Vluggen wrote:

                              I'd rather have them complain once and explain that it's a bug that will never resurface, than having a lot of exceptions (and invalid states) that I don't know of. I love the PHP-approach; either do or die, don't fake it.

                              This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

                              "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

                              L 1 Reply Last reply
                              0
                              • F Forbiddenx

                                I think we are misunderstanding each other. I do use specific exceptions but at times I also use the generic all exceptions.. But, I also bomb out if I use the generic all exception and stop everything in its tracks.

                                catch (Exception exc)
                                {
                                log it, or present it to the user exc...
                                BOMB OUT.... alert.. done.
                                I never resume operation that would be bad!
                                }

                                I only resume operation if I

                                catch (ExceptionTYPE exc)
                                {
                                try to recover..
                                }

                                Yes, it does add some extra code, but it is better then resuming you want to log any exception that occurs globally.

                                =)

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

                                Forbiddenx wrote:

                                But, I also bomb out if I use the generic all exception and stop everything in its tracks.

                                There's the problem; handling a "specific" exception means that you cannot use the generic exception to handle it - it'd be passing in other exceptions that weren't meant to be handled that way. Nice example is a Sql Server that's offline, and a client-app that keeps whining about a password being incorrect (since that was all that's handled locally). Hence, the best practice would be to catch and handle what you expect, and to log everything else on a higher level.

                                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                                1 Reply Last reply
                                0
                                • OriginalGriffO OriginalGriff

                                  Eddy Vluggen wrote:

                                  No-one advocates "not" checking them;

                                  Um.

                                  Eddy Vluggen wrote:

                                  And yes, I'd rather see my app die, than pretend nothing happened (and have it continue with corrupted data that gets saved later)

                                  Eddy Vluggen wrote:

                                  I'd rather have them complain once and explain that it's a bug that will never resurface, than having a lot of exceptions (and invalid states) that I don't know of. I love the PHP-approach; either do or die, don't fake it.

                                  This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

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

                                  OriginalGriff wrote:

                                  And yes, I'd rather see my app die, than pretend nothing happened (and have it continue with corrupted data that gets saved later)

                                  I do not advocate there that one should not handle exceptions. "Do or die" means that I'll try to close the app as gracefully as possible, with an apoligy to the user that an exception occured.

                                  OriginalGriff wrote:

                                  I'd rather have them complain once and explain that it's a bug that will never resurface

                                  Does still not mean that I do not have a global exception handler; it's implemented, but it does not "hide" exceptions and pretend all is well. It get's logged, and once investigated, one can easily push an update that ignores that specific exception if that's safe. Imagine medical software being like that, and using the "default gender" if that information is lost after an exception on a conversion.

                                  Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                                  J 1 Reply Last reply
                                  0
                                  • OriginalGriffO OriginalGriff

                                    I'm not saying "swallow it" and "pretend nothing happened". I'm saying use the tools and locate it while you (as a programmer) can still prevent it adversely affecting the user. Then report it, log it (both is good) and give them a chance to do something. Just letting your program crash is just being lazy! :laugh:

                                    This message is manufactured from fully recyclable noughts and ones. To recycle this message, please separate into two tidy piles, and take them to your nearest local recycling centre. Please note that in some areas noughts are always replaced with zeros by law, and many facilities cannot recycle zeroes - in this case, please bury them in your back garden and water frequently.

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

                                    OriginalGriff wrote:

                                    Just letting your program crash is just being lazy!

                                    Aight.

                                    Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                                    1 Reply Last reply
                                    0
                                    • S Srinivas Kalabarigi

                                      I dont have a habit of using try-cahtch block unless i am sure it throws an exception... is it advisable to use it in most places of your code.... what is the best practice?

                                      Srinivas K

                                      B Offline
                                      B Offline
                                      Brian Holsen
                                      wrote on last edited by
                                      #31

                                      Normally I don't us try-catch block. Except for exceptions I code myself and if there's something really not sure.

                                      1 Reply Last reply
                                      0
                                      • S Srinivas Kalabarigi

                                        I dont have a habit of using try-cahtch block unless i am sure it throws an exception... is it advisable to use it in most places of your code.... what is the best practice?

                                        Srinivas K

                                        V Offline
                                        V Offline
                                        V 0
                                        wrote on last edited by
                                        #32

                                        Try to avoid try-catch when you can. Often an if/else statement can help you out. (divide by zero, file exists, eof, ...) That doesn't mean you shouldn't use try/catch, but use them were appropriate. IOW some 'exceptional' thing might happen. (an object has a null value although it shouldn't, ... ) Hope this helps.

                                        V.
                                        (MQOTD Rules and previous Solutions )

                                        1 Reply Last reply
                                        0
                                        • L Lost User

                                          I'd rather have them complain once and explain that it's a bug that will never resurface, than having a lot of exceptions (and invalid states) that I don't know of. I love the PHP-approach; either do or die, don't fake it.

                                          Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                                          J Offline
                                          J Offline
                                          jschell
                                          wrote on last edited by
                                          #33

                                          Eddy Vluggen wrote:

                                          than having a lot of exceptions (and invalid states) that I don't know of.

                                          Been writing servers for 15 years, high capacity ones for 10, and I have never seen that. What I have seen are a lot of null pointer exceptions caused by programming adaptors in plugin architectures doing dynamic processing. Which means that the ALL transactions in flight would then fail simply because a one time data set caused a bug to show up. And I can note that in most cases the adapter code was not written by me but the plugin architecture was. I have seen catastrophic failures but they take the server down. And in that case catching the exceptions at least for the purpose of logging is critical.

                                          Eddy Vluggen wrote:

                                          I'd rather have them complain once and explain that it's a bug

                                          I rather not have to explain anything when all the customers suffered some sort of failure due to something that could have been avoided.

                                          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