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 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 Offline
    S Offline
    singh iz king
    wrote on last edited by
    #1

    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

    K J M S B 7 Replies 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

      K Offline
      K Offline
      killabyte
      wrote on last edited by
      #2

      what crappy code....

      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

        J Offline
        J Offline
        josda1000
        wrote on last edited by
        #3

        would the path ever get into the catch block anyway? wow lol i think my eyes just burned out.

        D 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
          molesworth
          wrote on last edited by
          #4

          What language is this? I thought it was C#, but there's no "get" or "set", and you can't declare local variables in a property.

          There are three kinds of people in the world - those who can count and those who can't...

          A 0 2 Replies Last reply
          0
          • J josda1000

            would the path ever get into the catch block anyway? wow lol i think my eyes just burned out.

            D Offline
            D Offline
            Dan Neely
            wrote on last edited by
            #5

            this.SomeItem.Details = new double[3]; MessageBox.Show(this.CrappyTotal);

            The European Way of War: Blow your own continent up. The American Way of War: Go over and help them.

            1 Reply Last reply
            0
            • M molesworth

              What language is this? I thought it was C#, but there's no "get" or "set", and you can't declare local variables in a property.

              There are three kinds of people in the world - those who can count and those who can't...

              A Offline
              A Offline
              Andrew Rissing
              wrote on last edited by
              #6

              He probably forgot to include the get/set because he was altering the code to post it up here. As for not declaring local variables in properties, you can.

              M S 2 Replies Last reply
              0
              • A Andrew Rissing

                He probably forgot to include the get/set because he was altering the code to post it up here. As for not declaring local variables in properties, you can.

                M Offline
                M Offline
                molesworth
                wrote on last edited by
                #7

                Andrew Rissing wrote:

                He probably forgot to include the get/set because he was altering the code to post it up here.

                Ah, OK - I was a bit confused (it's been a long day).

                Andrew Rissing wrote:

                As for not declaring local variables in properties, you can.

                Only inside a getter or setter, not as a "property local". I'm easily confused though... :)

                There are three kinds of people in the world - those who can count and those who can't...

                1 Reply Last reply
                0
                • M molesworth

                  What language is this? I thought it was C#, but there's no "get" or "set", and you can't declare local variables in a property.

                  There are three kinds of people in the world - those who can count and those who can't...

                  0 Offline
                  0 Offline
                  0x3c0
                  wrote on last edited by
                  #8

                  Perhaps he missed out the () at the end of the method name?

                  Between the idea And the reality Between the motion And the act Falls the Shadow

                  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

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

                    If the total is expected to always be computable, but it would be better to return -1 than to throw an exception if it isn't, how would you suggest coding it? Testing all four values to see if they're valid, testing to see whether any of the values is so big as to risk overflow, etc. would seem more complicated than just catching an exception. To be sure, such an approach would yield better performance in the case where an exception would be thrown and caught, but worse performance in the expected case where the total can be computed without difficulty. With regard to the relative wisdom of returning -1 versus propagating the exception, that would depend upon what the calling program is going to do with the information. It's not hard to imagine situations where having the function return -1 will be much cleaner than having it throw an exception, and others where the reverse would be true. BTW, one thing I would think would be useful in many situations where some callers would like exceptions handled and others would like them stifled would be for a method to accept a delegate to be called in case of trouble. Such a delegate could throw an exception if necessary, but could also handle some "trouble" situations better than would an exception.

                    L T 2 Replies Last reply
                    0
                    • S supercat9

                      If the total is expected to always be computable, but it would be better to return -1 than to throw an exception if it isn't, how would you suggest coding it? Testing all four values to see if they're valid, testing to see whether any of the values is so big as to risk overflow, etc. would seem more complicated than just catching an exception. To be sure, such an approach would yield better performance in the case where an exception would be thrown and caught, but worse performance in the expected case where the total can be computed without difficulty. With regard to the relative wisdom of returning -1 versus propagating the exception, that would depend upon what the calling program is going to do with the information. It's not hard to imagine situations where having the function return -1 will be much cleaner than having it throw an exception, and others where the reverse would be true. BTW, one thing I would think would be useful in many situations where some callers would like exceptions handled and others would like them stifled would be for a method to accept a delegate to be called in case of trouble. Such a delegate could throw an exception if necessary, but could also handle some "trouble" situations better than would an exception.

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

                      Except that you don't get an error on overflow, you just get PositiveInfinity (or NegativeInfinity), so the only thing that could throw an exception there is the indexing of this.SomeItem.Details You'd just have to test the length/count of that thing, whatever it is..

                      S 1 Reply Last reply
                      0
                      • A Andrew Rissing

                        He probably forgot to include the get/set because he was altering the code to post it up here. As for not declaring local variables in properties, you can.

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

                        Yup...rightly picked up. I forgot to include the get block :doh:

                        1 Reply Last reply
                        0
                        • S supercat9

                          If the total is expected to always be computable, but it would be better to return -1 than to throw an exception if it isn't, how would you suggest coding it? Testing all four values to see if they're valid, testing to see whether any of the values is so big as to risk overflow, etc. would seem more complicated than just catching an exception. To be sure, such an approach would yield better performance in the case where an exception would be thrown and caught, but worse performance in the expected case where the total can be computed without difficulty. With regard to the relative wisdom of returning -1 versus propagating the exception, that would depend upon what the calling program is going to do with the information. It's not hard to imagine situations where having the function return -1 will be much cleaner than having it throw an exception, and others where the reverse would be true. BTW, one thing I would think would be useful in many situations where some callers would like exceptions handled and others would like them stifled would be for a method to accept a delegate to be called in case of trouble. Such a delegate could throw an exception if necessary, but could also handle some "trouble" situations better than would an exception.

                          T Offline
                          T Offline
                          Thomas Weller 0
                          wrote on last edited by
                          #12

                          NEVER ever throw an exception to code a foreseeable condition - even if it might be rare. Exceptions are just not made for that, they are for error conditions! It's like knocking in a nail with a wrench: You might succeed somehow, but anyway this is hardly a good and recommendable practice...

                          supercat9 wrote:

                          how would you suggest coding it?

                          public double CrappyTotal // and yes, this 'Total' is an 'Average'
                          {
                          get
                          {
                          if (this.SomeItem.Details.Length < 4)
                          {
                          return -1;
                          }

                              return (this.SomeItem.Details\[0\].Value +	
                                      this.SomeItem.Details\[1\].Value +		
                                      this.SomeItem.Details\[2\].Value +		
                                      this.SomeItem.Details\[3\].Value) / 4;
                          }
                          

                          }

                          I really would feel ashamed to code this with an exception instead, it's just ugly and bad craftsmanship... 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 S 2 Replies 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

                            B Offline
                            B Offline
                            BadKarma
                            wrote on last edited by
                            #13

                            If I see such a thing i can say only one thing: "Everybody please remain calm! You Sir!! Get your hands up in the air and step away from the keyboard!"

                            Learn from the mistakes of others, you may not live long enough to make them all yourself.

                            S 1 Reply Last reply
                            0
                            • T Thomas Weller 0

                              NEVER ever throw an exception to code a foreseeable condition - even if it might be rare. Exceptions are just not made for that, they are for error conditions! It's like knocking in a nail with a wrench: You might succeed somehow, but anyway this is hardly a good and recommendable practice...

                              supercat9 wrote:

                              how would you suggest coding it?

                              public double CrappyTotal // and yes, this 'Total' is an 'Average'
                              {
                              get
                              {
                              if (this.SomeItem.Details.Length < 4)
                              {
                              return -1;
                              }

                                  return (this.SomeItem.Details\[0\].Value +	
                                          this.SomeItem.Details\[1\].Value +		
                                          this.SomeItem.Details\[2\].Value +		
                                          this.SomeItem.Details\[3\].Value) / 4;
                              }
                              

                              }

                              I really would feel ashamed to code this with an exception instead, it's just ugly and bad craftsmanship... 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
                              singh iz king
                              wrote on last edited by
                              #14

                              Hi Thomas, Thanks for that. The day I came across this, I had a private discussion with the developer and reasoned the right way of doing this. The message seems to be slowly getting across :)

                              1 Reply Last reply
                              0
                              • B BadKarma

                                If I see such a thing i can say only one thing: "Everybody please remain calm! You Sir!! Get your hands up in the air and step away from the keyboard!"

                                Learn from the mistakes of others, you may not live long enough to make them all yourself.

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

                                Lol...good one Unfortunately, I've come across so many such instances of bad programmers in my career (and I'm sure most of you have as well). This fortunately for me has been the only instance where the developer has understood what they've done wrong and positively taken on board the recommendations I've made. I actually came across this while doing a code review for a team that I had not worked with before.

                                1 Reply Last reply
                                0
                                • T Thomas Weller 0

                                  NEVER ever throw an exception to code a foreseeable condition - even if it might be rare. Exceptions are just not made for that, they are for error conditions! It's like knocking in a nail with a wrench: You might succeed somehow, but anyway this is hardly a good and recommendable practice...

                                  supercat9 wrote:

                                  how would you suggest coding it?

                                  public double CrappyTotal // and yes, this 'Total' is an 'Average'
                                  {
                                  get
                                  {
                                  if (this.SomeItem.Details.Length < 4)
                                  {
                                  return -1;
                                  }

                                      return (this.SomeItem.Details\[0\].Value +	
                                              this.SomeItem.Details\[1\].Value +		
                                              this.SomeItem.Details\[2\].Value +		
                                              this.SomeItem.Details\[3\].Value) / 4;
                                  }
                                  

                                  }

                                  I really would feel ashamed to code this with an exception instead, it's just ugly and bad craftsmanship... 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
                                  #16

                                  Thomas Weller wrote:

                                  NEVER ever throw an exception to code a foreseeable condition - even if it might be rare.

                                  I guess it depends what you mean by 'foreseeable'. Certainly if one could readily determine before performing an operation that it would throw an exception that one was planning on catching, and if there was any significant likelihood of such exception occurring, doing an early test before attempting the operation would be a good idea. Testing the length test on the array, for example, would seem appropriate, though in some applications that may be just about the only exception that could be guaranteed not to occur. On the other hand, it may not be possible to determine in advance all exceptions that might occur. In the code sample given, the '.Value' property could throw an exception (e.g. ObjectDisposed or whatever) even if the length of the array was valid. While a general 'Catch' would be icky, there are times when such a thing is appropriate. For example, in expression-evaluation window, nearly all exceptions thrown during expression evaluation should be caught. An application shouldn't die just because someone typed in an expression that caused an exception the application programmer hadn't foreseen. I don't particularly like -1 as a return value, but the overall style would seem appropriate for some applications.

                                  T 1 Reply Last reply
                                  0
                                  • L Lost User

                                    Except that you don't get an error on overflow, you just get PositiveInfinity (or NegativeInfinity), so the only thing that could throw an exception there is the indexing of this.SomeItem.Details You'd just have to test the length/count of that thing, whatever it is..

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

                                    You'd just have to test the length/count of that thing, whatever it is.. And you have to test all four items to ensure they're not null, and you'd have to somehow know in advance whether any attempt to read .Value might throw an exception of its own (I know properties aren't supposed to throw exceptions, but that doesn't mean they never will).

                                    L 1 Reply Last reply
                                    0
                                    • S supercat9

                                      You'd just have to test the length/count of that thing, whatever it is.. And you have to test all four items to ensure they're not null, and you'd have to somehow know in advance whether any attempt to read .Value might throw an exception of its own (I know properties aren't supposed to throw exceptions, but that doesn't mean they never will).

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

                                      Why would there be nulls in there? Well I suppose there could be nulls there, but then I'd still test for null rather than just die and later fix it with a catch..

                                      S 1 Reply Last reply
                                      0
                                      • L Lost User

                                        Why would there be nulls in there? Well I suppose there could be nulls there, but then I'd still test for null rather than just die and later fix it with a catch..

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

                                        harold aptroot wrote:

                                        Well I suppose there could be nulls there, but then I'd still test for null rather than just die and later fix it with a catch.

                                        There are all sorts of things that theoretically could go wrong, especially if the object supports inheritance. Checking in advance for all possible exceptions is frequently infeasible at best, and in many situations impossible (since even if the present implementation of a method can't throw an exception, a future override might). If no condition which would cause an exception is expected, such preemptive coding is often a waste of time (both programmer time and execution time). As for catching an exception and returning an error code versus letting the caller handle it, the latter approach is usually better but not always. If one's objective is to store the output of a function when it works, or -1 if it doesn't, which is nicer:

                                        StoreValue(theFunction()) ' Coded to return -1 in case of failure

                                        or

                                        Dim Result as Double
                                        Try
                                        Result = theFunction()
                                        Catch
                                        Result = -1
                                        End Try
                                        StoreValue(Result)

                                        I would consider the former approach to be much nicer.

                                        1 Reply Last reply
                                        0
                                        • S supercat9

                                          Thomas Weller wrote:

                                          NEVER ever throw an exception to code a foreseeable condition - even if it might be rare.

                                          I guess it depends what you mean by 'foreseeable'. Certainly if one could readily determine before performing an operation that it would throw an exception that one was planning on catching, and if there was any significant likelihood of such exception occurring, doing an early test before attempting the operation would be a good idea. Testing the length test on the array, for example, would seem appropriate, though in some applications that may be just about the only exception that could be guaranteed not to occur. On the other hand, it may not be possible to determine in advance all exceptions that might occur. In the code sample given, the '.Value' property could throw an exception (e.g. ObjectDisposed or whatever) even if the length of the array was valid. While a general 'Catch' would be icky, there are times when such a thing is appropriate. For example, in expression-evaluation window, nearly all exceptions thrown during expression evaluation should be caught. An application shouldn't die just because someone typed in an expression that caused an exception the application programmer hadn't foreseen. I don't particularly like -1 as a return value, but the overall style would seem appropriate for some applications.

                                          T Offline
                                          T Offline
                                          Thomas Weller 0
                                          wrote on last edited by
                                          #20

                                          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 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