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. Other Discussions
  3. The Weird and The Wonderful
  4. try-catch code convention [modified]

try-catch code convention [modified]

Scheduled Pinned Locked Moved The Weird and The Wonderful
career
30 Posts 21 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.
  • _ _beauw_

    Squelching exceptions can be a legitimate tactic. For example, suppose you're writing an error handling routine. The routine probably tries to do many things related to error handling: write out a log file, send an e-mail, etc. If any of these fails, you won't want this second failure to disrupt the rest of the error routine, nor will you want it to throw a new exception (which would quite likely propagate out to the OS level, and result in a GPF). Another legitimate reason to squelch is the existence of OS level bugs and failures that are outside the developer's control. There was a bug in Windows a few years that caused "insufficient memory" errors whenever the system entered "sleep" mode due to inactivity. I cannot really detect that as a .NET developer, except in the form of an "out of memory" exception. And the error condition is bogus, or at least temporary; so I do not want my program to GPF, I really do want it to ignore the exception and continue trying to operate. Squelching this error is legitimate, I think. I have had architect types tell me that exceptions should never be squelched. That simply doesn't square with reality for me, though. A better policy, I think, is to have guidelines for squelching exceptions, e.g. squelch only the most specific exception type possible, always put an explanatory comment in the "catch" block, don't use this tactic for simple validation of inputs, etc.

    modified on Saturday, July 3, 2010 12:33 PM

    J Offline
    J Offline
    Jammer 0
    wrote on last edited by
    #15

    I think the point was that it was in EVERY method ...

    Jammer My Blog | Articles | DMon | SampleSort

    _ 1 Reply Last reply
    0
    • J Jammer 0

      I think the point was that it was in EVERY method ...

      Jammer My Blog | Articles | DMon | SampleSort

      _ Offline
      _ Offline
      _beauw_
      wrote on last edited by
      #16

      Originally I think that was the point. The post I actually responded to seemed to impugn any and all squelching of exceptions ("[s]adly enough, I used to swallow exceptions in code as well..."). This blanket statement is actually one I hear a lot, even from people pretty well-placed in software development.

      1 Reply Last reply
      0
      • J Jon Sagara

        Kevin Drzycimski wrote:

        directly after the head opens a try block over the whole body. all errors are just thrown away.

        In Enterprise lingo, that's called the Try/Swallow pattern.

        Jon Sagara Some see the glass as half-empty, some see the glass as half-full. I see the glass as too big. -- George Carlin .NET Blog | Personal Blog | Articles

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

        Jon Sagara wrote:

        Try/Swallow

        I'm scared to reply to that one!

        Dave

        If this helped, please vote & accept answer!

        Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum.(Pete O'Hanlon)
        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

        Y 1 Reply Last reply
        0
        • B Bigdeak

          If you have common functions reachable by the GUI, that are not important for the main of the application, this is a really usefull and stable act, and i do it in almost the same manner for at least the common methods. For example i wan't to change a image of a specified object. Now my ChangeImage() method throws a unhandled exception, with this try catch block around the method body there will be no quaint exception message, the application won't crash because of a single method exception, only the ChangeImage() method isn't working. ;) Sorry for my bad english.

          _ Offline
          _ Offline
          _beauw_
          wrote on last edited by
          #18

          I think it's true that failures related to some less significant features should not be allowed to disrupt other features. Even logging these failures in a production environment can impact other critical systems. So, there are probably legitimate cases where errors related to an entire subsystem should be squelched in the production build. Doing this is, at some level, a revival of ON ERROR RESUME NEXT. At a minimum, I think that good programming practices dictate that unhandled exceptions should halt the program in its development builds (even if some of these are squelched in the "release" build). So long as the transition between build modes is automatic and reliable, this can be a good approach to exception handling for some applications.

          L 1 Reply Last reply
          0
          • K Kevin Drzycimski

            a fellow student told me of a strange code convention in his job: almost every single method looks like this

            //method head
            {
            try {
            //actual method body
            }
            catch (...) {
            }
            }

            directly after the head opens a try block over the whole body. all errors are just thrown away. the programs work and never crash! they are world market leader :-D seems this fast and easy developing is quite successfull at all. they are more engineers, so these kludges seem appropriate.

            modified on Thursday, July 1, 2010 2:57 PM

            K Offline
            K Offline
            Kunal Chowdhury IN
            wrote on last edited by
            #19

            try{} catch{} blocks should be use only when you need it. Else there will be a performance issue. It is not recommended to write try catch block for the whole code of any method. Where you expect to be a codeflaw, where exception may come just put your try catch there. Don't try to use generic exception in all the case. If you know some specific exception that may come, only catch those explicitly.

            Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


            Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

            1 Reply Last reply
            0
            • K Kevin Drzycimski

              a fellow student told me of a strange code convention in his job: almost every single method looks like this

              //method head
              {
              try {
              //actual method body
              }
              catch (...) {
              }
              }

              directly after the head opens a try block over the whole body. all errors are just thrown away. the programs work and never crash! they are world market leader :-D seems this fast and easy developing is quite successfull at all. they are more engineers, so these kludges seem appropriate.

              modified on Thursday, July 1, 2010 2:57 PM

              F Offline
              F Offline
              fjdiewornncalwe
              wrote on last edited by
              #20

              What you don't see, can't hurt you... It'll only hurt the guy who has to fix it.

              1 Reply Last reply
              0
              • _ _beauw_

                I think it's true that failures related to some less significant features should not be allowed to disrupt other features. Even logging these failures in a production environment can impact other critical systems. So, there are probably legitimate cases where errors related to an entire subsystem should be squelched in the production build. Doing this is, at some level, a revival of ON ERROR RESUME NEXT. At a minimum, I think that good programming practices dictate that unhandled exceptions should halt the program in its development builds (even if some of these are squelched in the "release" build). So long as the transition between build modes is automatic and reliable, this can be a good approach to exception handling for some applications.

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

                _beauw_ wrote:

                Even logging these failures in a production environment can impact other critical systems.

                ..logging doesn't require much resources (a small ringbuffer?), and should not influence the working of dependent systems. Having a global error handler that logs anything that's not expected helps a lot when maintaining the application.

                I are Troll :suss:

                _ 1 Reply Last reply
                0
                • D DaveyM69

                  Jon Sagara wrote:

                  Try/Swallow

                  I'm scared to reply to that one!

                  Dave

                  If this helped, please vote & accept answer!

                  Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum.(Pete O'Hanlon)
                  BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                  Y Offline
                  Y Offline
                  Yusuf
                  wrote on last edited by
                  #22

                  DaveyM69 wrote:

                  Jon Sagara wrote: Try/Swallow I'm scared to reply to that one! Dave

                  Promise, it won't swallow you, Dave. ;P

                  Yusuf May I help you?

                  1 Reply Last reply
                  0
                  • L Lost User

                    RugbyLeague wrote:

                    a great way to give the user the perception that all is right with the world.

                    That's the goal, according to some of the teachers here. If you find yourself in such a group, by all means, adapt or leave - you'll be the source of all bugs and errors if you try to move to structured error-handling :)

                    I are Troll :suss:

                    S Offline
                    S Offline
                    Stephen Hewitt
                    wrote on last edited by
                    #23

                    Eddy Vluggen wrote:

                    you'll be the source of all bugs and errors if you try to move to structured error-handling Smile

                    Fair point.

                    Steve

                    1 Reply Last reply
                    0
                    • K Kevin Drzycimski

                      a fellow student told me of a strange code convention in his job: almost every single method looks like this

                      //method head
                      {
                      try {
                      //actual method body
                      }
                      catch (...) {
                      }
                      }

                      directly after the head opens a try block over the whole body. all errors are just thrown away. the programs work and never crash! they are world market leader :-D seems this fast and easy developing is quite successfull at all. they are more engineers, so these kludges seem appropriate.

                      modified on Thursday, July 1, 2010 2:57 PM

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

                      Kevin Drzycimski wrote:

                      they are world market leader

                      Whatever sells! :sigh:

                      The funniest thing about this particular signature is that by the time you realise it doesn't say anything it's too late to stop reading it.

                      1 Reply Last reply
                      0
                      • L Lost User

                        RugbyLeague wrote:

                        a great way to give the user the perception that all is right with the world.

                        That's the goal, according to some of the teachers here. If you find yourself in such a group, by all means, adapt or leave - you'll be the source of all bugs and errors if you try to move to structured error-handling :)

                        I are Troll :suss:

                        K Offline
                        K Offline
                        Kevin Drzycimski
                        wrote on last edited by
                        #25

                        Eddy Vluggen wrote:

                        you'll be the source of all bugs and errors if you try to move to structured error-handling

                        so right^^ once turning on printing error messages to stderr, there was so much outpu - it was turned off immediately :laugh:

                        1 Reply Last reply
                        0
                        • L Lost User

                          _beauw_ wrote:

                          Even logging these failures in a production environment can impact other critical systems.

                          ..logging doesn't require much resources (a small ringbuffer?), and should not influence the working of dependent systems. Having a global error handler that logs anything that's not expected helps a lot when maintaining the application.

                          I are Troll :suss:

                          _ Offline
                          _ Offline
                          _beauw_
                          wrote on last edited by
                          #26

                          If you mean to say that every exception should be logged in every piece of software, or even in every .NET application, I just cannot endorse that view. Logging is I/O, which is a failure-prone and time-consuming category of operation. Consider what happens if I attempt to log inside of a deeply nested loop; some very bad things could happen, if the loop needs to continue executing on a real-time basis. In the "debug" build, everything can grind to a halt... in production, the time for that is over. Again, this is not necessarily a far-fetched scenario. There are .NET applications that control, or at least influence, real-time machinery. There are .NET programs that guide stock traders in real-time. Entering into an I/O routine is not always an acceptable response to failure in such environments, no matter how nice it sounds at the Airport Sheraton.

                          modified on Wednesday, July 14, 2010 7:43 PM

                          L 1 Reply Last reply
                          0
                          • _ _beauw_

                            If you mean to say that every exception should be logged in every piece of software, or even in every .NET application, I just cannot endorse that view. Logging is I/O, which is a failure-prone and time-consuming category of operation. Consider what happens if I attempt to log inside of a deeply nested loop; some very bad things could happen, if the loop needs to continue executing on a real-time basis. In the "debug" build, everything can grind to a halt... in production, the time for that is over. Again, this is not necessarily a far-fetched scenario. There are .NET applications that control, or at least influence, real-time machinery. There are .NET programs that guide stock traders in real-time. Entering into an I/O routine is not always an acceptable response to failure in such environments, no matter how nice it sounds at the Airport Sheraton.

                            modified on Wednesday, July 14, 2010 7:43 PM

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

                            _beauw_ wrote:

                            Logging is I/O, which is a failure-prone and time-consuming category of operation.Consider what happens if I attempt to log inside of a deeply nested loop;

                            I wouldn't expect a lot of unexpected exceptions in a deeply-nested loop.

                            _beauw_ wrote:

                            There are .NET applications that control, or at least influence, real-time machinery.

                            .NET isn't recommended for time-critical operations, but how many exceptions could the app raise per 50ms?

                            _beauw_ wrote:

                            There are .NET programs that guide stock traders in real-time. Entering into an I/O routine is not always an acceptable response to failure in such environments

                            I'm not talking about logging those exceptions that you handle locally, but those that you didn't expect and that don't get handled. There shouldn't be too many of those, and you wouldn't want to swallow those. Wouldn't want to ignore an divide by zero and price those stocks at "no worth" :)

                            I are Troll :suss:

                            1 Reply Last reply
                            0
                            • K Kevin Drzycimski

                              a fellow student told me of a strange code convention in his job: almost every single method looks like this

                              //method head
                              {
                              try {
                              //actual method body
                              }
                              catch (...) {
                              }
                              }

                              directly after the head opens a try block over the whole body. all errors are just thrown away. the programs work and never crash! they are world market leader :-D seems this fast and easy developing is quite successfull at all. they are more engineers, so these kludges seem appropriate.

                              modified on Thursday, July 1, 2010 2:57 PM

                              A Offline
                              A Offline
                              Alois Kraus
                              wrote on last edited by
                              #28

                              Sounds familar :) Perhaps you should add at least some tracing to your methods like this one Then your code would be transparent to exceptions but you can still see what exceptions did flow through your code without becoming much slower.

                                  public void Demo\_Show\_Leaving\_Trace\_With\_Exception()
                                  {
                                      TracerConfig.Reset("console");
                                      SomeMethod();
                                  }
                              
                                  void SomeMethod()
                                  {
                                      using (Tracer t = new Tracer(myType, "SomeMethod"))
                                      {
                                          SomeOtherMethod();
                                      }
                                  }
                              
                                  private void SomeOtherMethod()
                                  {
                                      using (Tracer t = new Tracer(myType, "SomeOtherMethod"))
                                      {
                                          FaultyMethod();
                                      }
                                  }
                              
                                  private void FaultyMethod()
                                  {
                                      throw new NotImplementedException("Hi this a fault");
                                  }
                              

                              The output would look the like this: 18:57:46.665 03064/05180 <{{ > ApiChange.IntegrationTests.Diagnostics.TracingTests.SomeMethod 18:57:46.668 03064/05180 <{{ > ApiChange.IntegrationTests.Diagnostics.TracingTests.SomeOtherMethod 18:57:46.670 03064/05180 < }}< ApiChange.IntegrationTests.Diagnostics.TracingTests.SomeOtherMethod Exception thrown: System.NotImplementedException: Hi this a fault at ApiChange.IntegrationTests.Diagnostics.TracingTests.FaultyMethod() at ApiChange.IntegrationTests.Diagnostics.TracingTests.SomeOtherMethod() at ApiChange.IntegrationTests.Diagnostics.TracingTests.SomeMethod() at ApiChange.IntegrationTests.Diagnostics.TracingTests.Demo_Show_Leaving_Trace_With_Exception() 18:57:46.670 03064/05180 < }}< ApiChange.IntegrationTests.Diagnostics.TracingTests.SomeOtherMethod Duration 2ms 18:57:46.689 03064/05180 < }}< ApiChange.IntegrationTests.Diagnostics.TracingTests.SomeMethod Duration 24ms That is a great time saver to find out where some exception did come from without the need to type try/catch(Exception ex) { LogException(ex);throw; } in many methods to find out where some exception did go through. Yours, Alois Kraus

                              1 Reply Last reply
                              0
                              • K Kevin Drzycimski

                                a fellow student told me of a strange code convention in his job: almost every single method looks like this

                                //method head
                                {
                                try {
                                //actual method body
                                }
                                catch (...) {
                                }
                                }

                                directly after the head opens a try block over the whole body. all errors are just thrown away. the programs work and never crash! they are world market leader :-D seems this fast and easy developing is quite successfull at all. they are more engineers, so these kludges seem appropriate.

                                modified on Thursday, July 1, 2010 2:57 PM

                                W Offline
                                W Offline
                                whatrevolution
                                wrote on last edited by
                                #29

                                Try/Swallow is an affective form of birth control.

                                Honestly Illustrated

                                <Pretentious> Raid tha manyuhl. :E <Pretentious> Aw raid eh own mah meaxbile. :E

                                1 Reply Last reply
                                0
                                • K Kevin Drzycimski

                                  a fellow student told me of a strange code convention in his job: almost every single method looks like this

                                  //method head
                                  {
                                  try {
                                  //actual method body
                                  }
                                  catch (...) {
                                  }
                                  }

                                  directly after the head opens a try block over the whole body. all errors are just thrown away. the programs work and never crash! they are world market leader :-D seems this fast and easy developing is quite successfull at all. they are more engineers, so these kludges seem appropriate.

                                  modified on Thursday, July 1, 2010 2:57 PM

                                  H Offline
                                  H Offline
                                  Hired Mind
                                  wrote on last edited by
                                  #30

                                  They've implemented the most efficient source of Mystery Errors ever devised.

                                  Before .NET 4.0, object Universe = NULL;

                                  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