Testing a method's return value after a call

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Noonga
    New Member
    • Dec 2008
    • 10

    Testing a method's return value after a call

    I have tried to follow this and read around but I have a simple question..

    I call method getIntField and return the value or exception, but I want to test that return.. If the value returned was not valid how to I trap and test that?

    Method called...

    [code=java]

    public int getIntField() {
    try {
    return Integer.parseIn t( searchStk.getTe xt());
    } catch (NumberFormatEx ception e) {
    message.setText ("" + searchStk.getTe xt() +"INVALID or wrong stock nbr, please re-enter...");
    return 0;
    }
    }
    [/code]

    I want to know what happened before I display the rest of my screen.

    Thanks!
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Can you put a try/catch around the place where you call getIntField()?
    If getIntField ever returns 0 on a normal run, you shouldn't return 0 when you have an error.
    Rather you should probably throw a new error after catching it, or rethrow the error. You can create your own Exception class if you want. Add a throws to your method declaration
    [code=java]

    public int getIntField() throws NumberFormatExc eption {
    try {
    return Integer.parseIn t( searchStk.getTe xt());
    } catch (NumberFormatEx ception e) {
    throw new NumberFormatExc eption("" + searchStk.getTe xt() +"INVALID or wrong stock nbr, please re-enter..."); //declare your new exception message
    }
    }
    [/code]

    Comment

    • Noonga
      New Member
      • Dec 2008
      • 10

      #3
      Ah, and then test if NumberFormatExc eption = x
      [code=java]

      if (NumberFormatEx ception = x) {
      do this
      }
      else {
      do that
      }
      [/code]

      Something like that?

      Comment

      • Noonga
        New Member
        • Dec 2008
        • 10

        #4
        Nope, that didn't work. Ok, maybe I missed the exit ramp on this one. Here are the two methods I had so far..

        [code=java]
        private void searchButtonAct ionPerformed(ja va.awt.event.Ac tionEvent evt) {
        function = "search";
        getIntField();
        if (NumberFormatEx ception == "Invalid Number") {
        message.setText ("Invalid!!! ");
        }
        else {
        recsel = Integer.parseIn t(searchStk.get Text());
        searchStk.setTe xt("");
        recsel = recsel - 1;
        displayRec( recsel );
        }
        }
        [/code]

        and...

        [code=java]
        public int getIntField() throws NumberFormatExc eption {
        try {
        return Integer.parseIn t( searchStk.getTe xt());
        } catch (ArrayIndexOutO fBoundsExceptio n e) {
        message.setText ("Record not found");
        return 0;
        } catch (NumberFormatEx ception e) {
        throw new NumberFormatExc eption("Invalid Number");
        }
        }
        [/code]

        Am I not getting this at all? heh, I know the light will come on soon.

        This is what I get...
        Exception in thread "AWT-EventQueue-0" java.lang.Numbe rFormatExceptio n: Invalid Number

        Comment

        • Noonga
          New Member
          • Dec 2008
          • 10

          #5
          Ok, quick update...

          Doing this instead..

          [code=java]
          try {
          getIntField();
          } catch (ArrayIndexOutO fBoundsExceptio n e) {
          message.setText ("Record not found");
          } catch (NumberFormatEx ception e) {
          message.setText ("Invalid Record, re-enter");
          }
          // recsel = Integer.parseIn t(searchStk.get Text());
          // searchStk.setTe xt("");
          // recsel = recsel - 1;
          // displayRec( recsel );
          }
          [/code]

          Now to figure out where the code goes when no exception is found and the user has input the proper information...

          Getting there!

          Comment

          • Noonga
            New Member
            • Dec 2008
            • 10

            #6
            Fixed!!!!!!!!!

            ok, got it.. had to dig deeep to find an example of how to add the code if there were no exceptions.....

            Thanks!

            [code=java]
            private void searchButtonAct ionPerformed(ja va.awt.event.Ac tionEvent evt) {
            function = "search";

            try {
            Integer.parseIn t( searchStk.getTe xt());
            recsel = Integer.parseIn t(searchStk.get Text());
            searchStk.setTe xt("");
            recsel = recsel - 1;
            displayRec( recsel );
            } catch (ArrayIndexOutO fBoundsExceptio n e) {
            message.setText ("Record not found");
            } catch (NumberFormatEx ception e) {
            message.setText ("Invalid Record, re-enter");
            }
            }
            [/code]

            Comment

            • Noonga
              New Member
              • Dec 2008
              • 10

              #7
              ok, that worked, but not like I wanted, so before I post again guess I will try to look further. I did not want the following code to execute unless there were no exceptions..

              [code=java]
              recsel = Integer.parseIn t(searchStk.get Text());
              searchStk.setTe xt("");
              recsel = recsel - 1;
              displayRec( recsel );
              [/code]

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Think about what you expect that method to return:

                1) an arbitrary integer or
                2) a failure status

                If you can sacrifice one int value to indicate a failure status you can map all possible return values to the int domain: e.g. x == Integer.MIN_VAL UE indicates a failure status otherwise x is the int return value for the method.

                If you can't find such a sentinel value think classes; make your method return an instance of this class:

                Code:
                class ReturnValue {
                   private int x;
                   private boolean failure;
                   //
                   ReturnValue() { failure= true; }
                   ReturnValue(int x) { this.x= x; }
                   //
                   boolean isFailure() { return failure; }
                   int getX() { return x; }
                }
                Your method will look something like this:

                Code:
                ReturnValue yourMethod( ... )
                   try {
                      return new ReturnValue(Integer.parseInt( ... ));
                   }
                   catch (Exception e) {
                      return new ReturnValue();
                   }
                }
                ... and the callers of this method can check the 'validity' of the returned value and, if no error occurred, get the int value from the ReturnValue object. Classes and objects aren't part of the language for no reason.

                kind regards,

                Jos

                Comment

                • Noonga
                  New Member
                  • Dec 2008
                  • 10

                  #9
                  Oh, thanks Jos!

                  I did play around with it and ended up returning an int value and then using that value to determine the path to take, similiar to what you mentioned.

                  I will pluck away at the code next week, but I really do appreciate the input.. your code is much smoother than what I did!

                  Comment

                  Working...