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. !(How to best use a try catch block) [modified]

!(How to best use a try catch block) [modified]

Scheduled Pinned Locked Moved The Weird and The Wonderful
tutorial
26 Posts 14 Posters 2 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.
  • T Thomas Weller 0

    supercat9 wrote:

    On the other hand, it may not be possible to determine in advance all exceptions that might occur.

    Of course not. In that case we wouldn't need exceptions at all... What I mean is: 'Foreseeable' in terms of business/application logic. If something totally unexpected happens (like e.g. the 'ObjectDisposed' you mentioned), there should be a general top level exception handler at the application level, but for sure such an exception must never be swallowed silently by the executing code. Not in a million years, in no circumstance whatsoever!

    supercat9 wrote:

    I don't particularly like -1 as a return value

    Same with me, but in the case of my example -1 has a clear, discrete meaning that can de documented (less than 4 items -> computation not possible), while in the original snippet -1 means sth. went wrong (and I will never tell you what the problem was...). That's a huge difference - especially on large business-scale software projects, where you might have hundreds of such properties... Regards Thomas

    www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
    Programmer - an organism that turns coffee into software.

    S Offline
    S Offline
    supercat9
    wrote on last edited by
    #21

    If something totally unexpected happens (like e.g. the 'ObjectDisposed' you mentioned), there should be a general top level exception handler at the application level, but for sure such an exception must never be swallowed silently by the executing code. Not in a million years, in no circumstance whatsoever! That depends what one is trying to do. Would people like Visual Studio very much if it died any time an exception occurred while evaluating expressions in the Watch window? Or is the proper action to show the problematic expression with an indication that it cannot be evaluated? If a program is supposed to graph a function, it may at times be unclear the best way to handle an exception. If one is trying to graph an expression like f(x)=1/x, it's best that the problematic case at x=0 be swallowed, while graphing is allowed to continue on the other side. On the other hand, if the function is one which will always throw an exception, calling the function 1,000 times while drawing the graph will cause 1,000 exceptions to be thrown. Swallowing exceptions in a fashion that hides any indication of what type of exception occurred seems like a bad idea, but it would seem there are many situations where a calling application is merely interested in whether or not an operation worked, and not what went wrong if it didn't.

    OriginalGriffO 1 Reply Last reply
    0
    • S singh iz king

      Just came across a class which has tens of such properties. These properties are called by other classes and by other properties / methods of this class!!! Oh! and also look how the property name says total, but is actually returning an average :omg:

      public double CrappyTotal
      {
      double CrappyTotal = 0; // notice the name of the variable is the same as the property
      try
      {
      CrappyTotal = this.SomeItem.Details[0].Value;
      CrappyTotal += this.SomeItem.Details[1].Value;
      CrappyTotal += this.SomeItem.Details[2].Value;
      CrappyTotal += this.SomeItem.Details[3].Value;
      CrappyTotal = CrappyTotal / 4;
      }
      catch
      {
      CrappyTotal = -1;
      }
      return CrappyTotal;
      }

      modified on Wednesday, July 8, 2009 11:35 PM

      U Offline
      U Offline
      User 4483848
      wrote on last edited by
      #22

      I don't like returning -1 for an error (particularly in this case) because -1 could be a valid result. eg. the values are all -1. There are a couple of nice solutions I can think of. One would be to use a nullable type ie. double?. The other way would be to let an exception be thrown or throw your own exceptions. Only looking at the first four elements is probably the worst thing IMHO though. What do you think of this?

      public double CrappyTotal
      {
      get
      {
      double total = 0;

          foreach (var d in this.SomeItem.Details)
          {
              total += d.Value;
          }
      
          return total / (double)this.SomeItem.Details.Count;
      }
      

      }

      No exception handling :mad:. I would be happy without error handling. I could add a check for nulls at the start, but I don't think it's worth the time. It would probably depend how and where it was being used though. So, are there people out there who insist that every exception must be handled?

      S 1 Reply Last reply
      0
      • S supercat9

        If something totally unexpected happens (like e.g. the 'ObjectDisposed' you mentioned), there should be a general top level exception handler at the application level, but for sure such an exception must never be swallowed silently by the executing code. Not in a million years, in no circumstance whatsoever! That depends what one is trying to do. Would people like Visual Studio very much if it died any time an exception occurred while evaluating expressions in the Watch window? Or is the proper action to show the problematic expression with an indication that it cannot be evaluated? If a program is supposed to graph a function, it may at times be unclear the best way to handle an exception. If one is trying to graph an expression like f(x)=1/x, it's best that the problematic case at x=0 be swallowed, while graphing is allowed to continue on the other side. On the other hand, if the function is one which will always throw an exception, calling the function 1,000 times while drawing the graph will cause 1,000 exceptions to be thrown. Swallowing exceptions in a fashion that hides any indication of what type of exception occurred seems like a bad idea, but it would seem there are many situations where a calling application is merely interested in whether or not an operation worked, and not what went wrong if it didn't.

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

        supercat9 wrote:

        Would people like Visual Studio very much if it died any time an exception occurred while evaluating expressions in the Watch window? Or is the proper action to show the problematic expression with an indication that it cannot be evaluated?

        I'm not sure what your argument is here. VS dying under those circumstances isn't "swallowing the exception", it is ignoring it completely. VS reporting the problem isn't swallowing the exception either, it is processing it and reporting the existance of a problem - exactly what exceptions are there for. Swallowing an exception is (IMHO) "pretending it didn't happen" and carrying on regardless. If a problem occurs saving my work every ten minutes and the exception gets swallowed, I am going to be a very unhappy bunny when I find out later it was all lost!

        No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones

        "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

        S 1 Reply Last reply
        0
        • U User 4483848

          I don't like returning -1 for an error (particularly in this case) because -1 could be a valid result. eg. the values are all -1. There are a couple of nice solutions I can think of. One would be to use a nullable type ie. double?. The other way would be to let an exception be thrown or throw your own exceptions. Only looking at the first four elements is probably the worst thing IMHO though. What do you think of this?

          public double CrappyTotal
          {
          get
          {
          double total = 0;

              foreach (var d in this.SomeItem.Details)
              {
                  total += d.Value;
              }
          
              return total / (double)this.SomeItem.Details.Count;
          }
          

          }

          No exception handling :mad:. I would be happy without error handling. I could add a check for nulls at the start, but I don't think it's worth the time. It would probably depend how and where it was being used though. So, are there people out there who insist that every exception must be handled?

          S Offline
          S Offline
          singh iz king
          wrote on last edited by
          #24

          Yes, That is one of the ways I suggested, but also added that if you are calculating an average, then the name should probably reflect that as well :)

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            supercat9 wrote:

            Would people like Visual Studio very much if it died any time an exception occurred while evaluating expressions in the Watch window? Or is the proper action to show the problematic expression with an indication that it cannot be evaluated?

            I'm not sure what your argument is here. VS dying under those circumstances isn't "swallowing the exception", it is ignoring it completely. VS reporting the problem isn't swallowing the exception either, it is processing it and reporting the existance of a problem - exactly what exceptions are there for. Swallowing an exception is (IMHO) "pretending it didn't happen" and carrying on regardless. If a problem occurs saving my work every ten minutes and the exception gets swallowed, I am going to be a very unhappy bunny when I find out later it was all lost!

            No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones

            S Offline
            S Offline
            supercat9
            wrote on last edited by
            #25

            VS reporting the problem isn't swallowing the exception either, it is processing it and reporting the existance of a problem - exactly what exceptions are there for. The "-1" return seems overly vague as to what problem occurred when computing the data, but it does indicate that a problem occurred. I would not expect the caller of a function like the one given to ignore the return value. It may not process it particularly as an error, but it would probably store it someplace. Suppose the objective is to produce a table showing various data associated with a bunch of people; for whatever reason, certain data will be unavailable for certain people. Exceptions would be appropriate if one's objective was to leave unprocessed any person for whom some information could not be retrieved correctly. Return codes are more appropriate if the objective is to produce a table in which computable values are filled in and uncomputable values show "N/A".

            1 Reply Last reply
            0
            • S singh iz king

              Just came across a class which has tens of such properties. These properties are called by other classes and by other properties / methods of this class!!! Oh! and also look how the property name says total, but is actually returning an average :omg:

              public double CrappyTotal
              {
              double CrappyTotal = 0; // notice the name of the variable is the same as the property
              try
              {
              CrappyTotal = this.SomeItem.Details[0].Value;
              CrappyTotal += this.SomeItem.Details[1].Value;
              CrappyTotal += this.SomeItem.Details[2].Value;
              CrappyTotal += this.SomeItem.Details[3].Value;
              CrappyTotal = CrappyTotal / 4;
              }
              catch
              {
              CrappyTotal = -1;
              }
              return CrappyTotal;
              }

              modified on Wednesday, July 8, 2009 11:35 PM

              M Offline
              M Offline
              mateotrek
              wrote on last edited by
              #26

              Unaveragely craptastic!

              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