我应该如何处理 java 中的 NumberFormatException?

How should I handle NumberFormatException in java?

有没有办法处理NumberFormatException的数量(顺序)?我用 Double operand[] 制作了一个计算器,如下所示,我想写下错误发生的时间。当我输入“2+k”时,应该会出现 "operand[1] has the wrong input." 的消息。我应该怎么做?

首先,替换行

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

与行

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

现在您可以在使用 NumberFormatException(String) 构造函数在 MyCalculator.calculate() 方法中抛出异常时传递消息。它看起来像这样:

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
}

也许你可以定义一个新的异常。例如 CalculatorException 可以包含有关计算的更多具体信息,例如哪个操作数不正确。或者您甚至可以再定义一个异常 IllegalOperandException,它可以扩展 CalculatorException。然后你的方法 calculate 可以声明为抛出 CalculatorException。总之,我们的想法是定义一个新的异常层次结构,以提供与您的问题领域更相关的信息。

然后,你的代码可能是这样的:

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