Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: Problems with Try/Catch Catching Wrong Exception

  1. #1
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Problems with Try/Catch Catching Wrong Exception

    This is a test build for a new version of the calculator application in which I am trying to implement dynamic mode switching (fairly standard... subtract your total while in addition mode). I'm basically rewriting the entire Arithmetic.java class so that all of the methods have return types rather than declaring them void.

    This current test build implements only addition and subtraction with a temporary main method (for testing purposes). Mathematically it works fine. The problem arises with the Try/Catch layout.

    [CODE]
    public class Arithmetic {
      public Double Add(double totNum) {
        boolean calc = true;
        while(calc == true) {
          try {
            CalcInput user = new CalcInput();
            String userInput = user.getUserInput(" ");
            if(userInput.equals("-")) {
              System.out.println(totNum + "-");
              double result = Subtract(totNum);
              totNum = result;
            } else {}
            double addNum = Double.parseDouble(userInput);
            if(totNum == 0) {
              System.out.println(addNum + "+");
            } else {
              System.out.println(totNum + "+" + addNum);
            }
            totNum = totNum + addNum;
          } catch(NumberFormatException e) {
            System.out.println("Invalid input!  Check to make sure you typed it correctly and try again!");
            System.out.println("-DO NOT use operators.  Enter your NUMERICAL input and press ENTER.");
            System.out.println("-You may use shortcuts to call other calculation modes.  (+, -, x, etc.");
          } catch(NullPointerException e) {
            calc = false;
          }
        }
        return totNum;
      }
      public Double Subtract(double totNum) {
        boolean calc = true;
        while(calc == true) {
          try {
            CalcInput user = new CalcInput();
            String userInput = user.getUserInput(" ");
            if(userInput.equals("+")) {
              System.out.println(totNum + "+");
              double result = Add(totNum);
              totNum = result;
            } else {}
            double addNum = Double.parseDouble(userInput);
            if(totNum == 0) {
              System.out.println(addNum + "-");
              totNum = addNum;
            } else {
              System.out.println(totNum + "-" + addNum);
              totNum = totNum - addNum;
            }
          } catch(NumberFormatException e) {
            System.out.println("Invalid input!  Check to make sure you typed it correctly and try again!");
            System.out.println("-DO NOT use operators.  Enter your NUMERICAL input and press ENTER.");
            System.out.println("-You may use shortcuts to call other calculation modes.  (+, -, x, etc.");
          } catch(NullPointerException e) {
            calc = false;
          }
        }
        return totNum;
      }
      public static void main(String[] args) {
        Arithmetic a = new Arithmetic();
        double result = a.Add(0);
        System.out.println(result);
      }
    }
    [/CODE]

    If you call the subtraction method while in the addition mode and press ENTER with nothing in the input field (which I would assume to be a NullPointerException), it displays the error message I added for the NumberFormatException.

    Why is that? Is it because you are operating within a call? In that case, how do I get out of the called method so that the person can hit ENTER and get the result?

    If it isn't clear yet what the problem is, I will try to clarify a bit more:
    While in the program....
    //I enter 5. The system prints the response as usual.
    5.0+
    //I enter 5 again. Still working fine.
    5.0+5.0
    //I enter - The call works fine.
    10.0-
    //I enter 5. Still lookin good.
    10.0-5
    //I hit ENTER (no input). Here is where it goes to hell.
    It displays the error message I implemented in the NumberFormatException catch.
    //I hit ENTER again. NOW it gets it.
    5.0 <----- It got the right answer!

    But it's recognizing a NullPointerException as a NumberFormatException while inside the method call.

    Any help would be appreciated.

    EDIT: I did just realize there are two loops within the try/catch. So the problem probably comes from the fact that it's trying to end the first loop before the inner loop is done executing. But, how do I fix that and/or why is it displaying the defined catch for NumberFormatException?
    Last edited by bgroenks96; June 9th, 2011 at 02:33 PM. Reason: Added information.


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    In my opinion you should never catch a NPE or any other RuntimeException. They are an indication that there is a serious flaw in the programs logic that should be fixed rather than catch it and carry on as if things are OK.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    it's recognizing a NullPointerException as a NumberFormatException while inside the method call.
    Add a printStackTrace to see exactly where the error is occurring.

  4. The Following User Says Thank You to Norm For This Useful Post:

    bgroenks96 (June 10th, 2011)

  5. #4
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Quote Originally Posted by Junky View Post
    In my opinion you should never catch a NPE or any other RuntimeException. They are an indication that there is a serious flaw in the programs logic that should be fixed rather than catch it and carry on as if things are OK.
    If you could point out the fatal logic flaw that would be great...

  6. #5
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Quote Originally Posted by Norm View Post
    Add a printStackTrace to see exactly where the error is occurring.
    I inserted a print line with ("Exception: " + e.getMessage()) and a e.printStackTrace after the NumberFormatException catch and was rewarded with this:
    Exception: For input string: "-"
    java.lang.NumberFormatException: For input string: "-"
            at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:12
    22)
            at java.lang.Double.parseDouble(Double.java:510)
            at Arithmetic.Add(Arithmetic.java:13)
            at Arithmetic.main(Arithmetic.java:63)

    Which I found interesting since the if statement for the "-" is before the parseDouble action. I don't see why the "-" input should be causing a problem with the parsing method?

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Could you make a version of your code that uses the Scanner class with a String defining the input so that others could test the code without having to go to console mode and spoon feed the program by typing in stuff hoping to get the right combination to create the error?
    For example:


    Scanner input = new Scanner("john\n70\n50\nstop\n\n\n\n"); //System.in);

  8. #7
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    I don't know where or when you code could possibly throw a NPE. If your code does throw a NPE then you need to track down where it is, why it is happening and fix it. Just adding a catch clause to handle NPE is a poor option.

    All this is commenting upon your coding style and has nothing to do with your actual problem because as you have witnessed you are not getting a NPE but rather a NumberFormatException. Once again it is your code and therefore your job to find out why you get such an exception and fix the problem.

  9. #8
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Quote Originally Posted by bgroenks96 View Post
    I don't see why the "-" input should be causing a problem with the parsing method?
    Really????

    You cannot see that trying to parse "-" to a double will throw a NumberFormatException. In that case please inform us to what number you think "-" represents.

  10. #9
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Well, I found at least 2 errors in this code that should be fixed:

    public Double Subtract(double totNum) {
        boolean calc = true;
        while(calc == true) {
          try {
            CalcInput user = new CalcInput();
            String userInput = user.getUserInput(" ");
            if(userInput.equals("+")) {
              System.out.println(totNum + "+");
              double result = Add(totNum);
              totNum = result;
            } else {}
            double addNum = Double.parseDouble(userInput);
            if(totNum == 0) {
              System.out.println(addNum + "-");
              totNum = addNum;
            } else {
              System.out.println(totNum + "-" + addNum);
              totNum = totNum - addNum;
            }
          } catch(NumberFormatException e) {
            System.out.println("Invalid input!  Check to make sure you typed it correctly and try again!");
            System.out.println("-DO NOT use operators.  Enter your NUMERICAL input and press ENTER.");
            System.out.println("-You may use shortcuts to call other calculation modes.  (+, -, x, etc.");
          } catch(NullPointerException e) {
            calc = false;
          }
        }
        return totNum;
      }

    First off, calc appears to never be set to false unless a Null Pointer Exception is thrown, so unless one is thrown, your while loop should go forever. Was that done on purpose?

    It would be better if calc were set to false at the end of each of the if and else things in your try block or something. That way it will exit only if the Exceptions aren't thrown, not just if a Null Pointer Exception is thrown.

    Second, those two brackets after that first else statement serve no purpose, except to probably mess up your code by making sure that everything after it was not inside your else block like you probably intended.

    Ok, so you are getting NumberFormatException.

    Yeah,

    "-" isn't very helpful to a compiler.

    First off negative what? Second, to the compiler, without any number attached to it, it will think that you entered in a String and it wants you to use a double.

    That's why it said:

    For input string: "-"

    I think I see what your program is trying to do however. Correct me if I'm wrong, but you want the user to enter like "+" or "-" or something and then user that operator to perform some calculation.

    Well, what you're doing might work if you fixed those two errors I pointed out above, particularly the bracket error, though the other one needs fixing too to avoid a potential infinite loop.
    Last edited by javapenguin; June 9th, 2011 at 10:12 PM. Reason: Realized that you were getting NumberFormatException

  11. The Following User Says Thank You to javapenguin For This Useful Post:

    bgroenks96 (June 10th, 2011)

  12. #10
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Actually, I've noticed that you appear to have an else block in both your Add and Subtract methods that appears to do nothing.

  13. #11
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    If the user inputs nothing it throws a NPE. That is the only reason the catch is there. If nothing is put in the input, then it tries to pass a null value to the parsing method which throws a NPE. Seems logical to have a catch to prevent the program from crashing upon this event. It's there in the interest of user stupidity (or in the most recent build it's how you get the output).
    Last edited by bgroenks96; June 10th, 2011 at 05:41 PM.

  14. #12
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Quote Originally Posted by Junky View Post
    Really????

    You cannot see that trying to parse "-" to a double will throw a NumberFormatException. In that case please inform us to what number you think "-" represents.
    ..............

    I am not stupid. YES I understand that you can't parse a symbol to a double. DUH.

    But, the error was happening when you hit ENTER with no input. Therefore, you would expect a NPE. However, what I determined is that when you hit ENTER it was attempting to close the original while loop but you are in a different loop. The loop you are in has to finish executing before you can close the one before IT.

    This whole code was a mess of loops interfering with each other. The design worked fine back in v.1.2 but it doesn't work with integrating dynamic functions.

    So I rewrote the whole thing. It now has ONE looping method that calls void methods upon the users input of a specified operator. It uses three static variables to keep track of the inputs. Works quite well.

    In the end, this issue is no longer relevant because the code has been rewritten.

    I will mark the thread as solved.

  15. #13
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Oh and additional note...

    Thank you to everyone who tried to help in this thread. Your ideas may or may not have worked, but I opted to just rewrite the Artihmetic class to make a cleaner design that would work with dynamic functions.

    Thanks for your time!

  16. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    you would expect a NPE
    Most programmers do NOT expect a NPE. They add code to test ALL data that is read and to handle all cases that they can think of. Bad input is very common and should be handled in the main code, not as an exception.

  17. #15
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: Problems with Try/Catch Catching Wrong Exception

    Quote Originally Posted by Norm View Post
    Most programmers do NOT expect a NPE. They add code to test ALL data that is read and to handle all cases that they can think of. Bad input is very common and should be handled in the main code, not as an exception.
    Yes I know.

    I know a lot more now about user input than I did back when I first started this program. I basically just used a code given in the beginning sections of my book to do so. Looking at it now, I can see it was used for trivial purposes, and I should probably tweek it to improve efficiency. The issue is that right now that reader code returns a null value if the input line contains nothing. I could (and will) change that, but it will require a good deal of editing to the rest of my code.

    The point is that the catch works for right now. Don't worry though, rewriting the reader code to get rid of the null return is on my list of efficiency improvements for this program.

    I realize it's not the best programming practice, and I will fix it!

    But right now, I have other parts of the code that need tweeking as well some things to finish adding.

Similar Threads

  1. Quick question with throwing and catching an exception.
    By Andyandhisboard in forum What's Wrong With My Code?
    Replies: 6
    Last Post: May 12th, 2011, 10:24 PM
  2. What is Wrong With My Exception Class Code?
    By Allicat in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 5th, 2011, 10:09 AM
  3. [SOLVED] Handling Errors / calling Error-Catching Methods
    By movsesinator in forum Object Oriented Programming
    Replies: 4
    Last Post: April 6th, 2010, 05:35 AM
  4. Exception and Serialization Problems
    By chrisych in forum Exceptions
    Replies: 0
    Last Post: February 7th, 2010, 11:30 AM
  5. Replies: 2
    Last Post: November 19th, 2009, 11:55 PM