-1

Is there a way to handle the number(order) of NumberFormatException? I made a calculator using Double operand[], and like below, I want to write when did error occurred. When I put the input "2+k", the message saying that "operand[1] has the wrong input." should come out. How should I do like that?

  • You may want to validate that the input is numeric before passing it to your calculator. If you search on SO for something like check if a string is numeric you'll find lots of examples. – Rob H Jun 04 '16 at 15:39
  • Apparently the `calculate()` method converts the operands to doubles? It may be possible to catch the exceptions there seperately and rethrow them with the explicit message that you want. Like `throw new NumberFormatException(String.format("operand[%d] has the wrong input.", operandIndex));`. Then you could just catch the `NumberFormatException` here and print its message. Like Paul's answer but without validating the input yourself. Just stuff them in a `double` and catch/rethrow the exception. – Arjan Jun 04 '16 at 15:48

2 Answers2

0

First, replace the line

System.out.println("operand[] has the wrong input.");

with the line

System.out.println(e.getMessage());

Now you can pass a message when you throw the exception in the MyCalculator.calculate() method using the NumberFormatException(String) constructor. It would look something like this:

calculate(String expression)
{
    //validate input code
    //...

    //if operand 0 not valid
    throw new NumberFormatException("operand 0 has the wrong input");

    //if operand 1 not valid
    throw new NumberFormatException("operand 1 has the wrong input");

    //rest of calculate method
}
Paul
  • 134
  • 4
0

Maybe you could define a new exception. As for example CalculatorException which could contain more specific information about calculations, as for example which operand is incorrect. Or you could even define one more exception like IllegalOperandException which could extend CalculatorException. And then your method calculate could be declared to throw a CalculatorException. In conclusion, the idea is to define a new hierarchy of exceptions to give information more related to the domain of your problem.

And then, your code could be so:

try {
    System.out.println("result: " + MyCalculator.calculate(expression));
    System.out.println();
} catch(CalculatorException e) {
    System.out.println(e.getMessage());
}