Jamie Heminston Jamie Heminston - 1 month ago 7
Java Question

How should I handle NumberFormatException in java?

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?

Answer

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