# Problems with Try/Catch Catching Wrong Exception

• June 9th, 2011, 02:22 PM
bgroenks96
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 java:

```[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?
• June 9th, 2011, 06:41 PM
Junky
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.
• June 9th, 2011, 08:31 PM
Norm
Re: Problems with Try/Catch Catching Wrong Exception
Quote:

it's recognizing a NullPointerException as a NumberFormatException while inside the method call.
Add a printStackTrace to see exactly where the error is occurring.
• June 9th, 2011, 08:46 PM
bgroenks96
Re: Problems with Try/Catch Catching Wrong Exception
Quote:

Originally Posted by Junky
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...
• June 9th, 2011, 09:02 PM
bgroenks96
Re: Problems with Try/Catch Catching Wrong Exception
Quote:

Originally Posted by Norm
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:
Code :

```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?
• June 9th, 2011, 09:10 PM
Norm
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);
• June 9th, 2011, 09:11 PM
Junky
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.
• June 9th, 2011, 09:14 PM
Junky
Re: Problems with Try/Catch Catching Wrong Exception
Quote:

Originally Posted by bgroenks96
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.
• June 9th, 2011, 09:45 PM
javapenguin
Re: Problems with Try/Catch Catching Wrong Exception
Well, I found at least 2 errors in this code that should be fixed:

Code java:

```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.
• June 9th, 2011, 10:21 PM
javapenguin
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.
• June 10th, 2011, 05:34 PM
bgroenks96
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).
• June 10th, 2011, 05:38 PM
bgroenks96
Re: Problems with Try/Catch Catching Wrong Exception
Quote:

Originally Posted by Junky
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.
• June 10th, 2011, 05:40 PM
bgroenks96
Re: Problems with Try/Catch Catching Wrong Exception

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.

• June 10th, 2011, 05:44 PM
Norm
Re: Problems with Try/Catch Catching Wrong Exception
Quote:

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.
• June 10th, 2011, 08:08 PM
bgroenks96
Re: Problems with Try/Catch Catching Wrong Exception
Quote:

Originally Posted by Norm
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.