Jamie Heminston Jamie Heminston - 1 year ago 68
Java Question

How should I handle NumberFormatException in java?

Is there a way to handle the number(order) of

? I made a calculator using
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 Source

First, replace the line

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

with the line


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download