如何正确抛出异常

时间:2015-09-30 20:19:38

标签: java

我是java的新手,我正在尝试解决程序中可能出现的错误。我正在创建一个计算器并将输入从中缀转换为后缀来计算结果。我想尝试在输入中考虑不匹配的括号,但我遇到了麻烦。例如,当从中缀转换为后缀时,当达到)时,它将从堆栈中弹出数字并将它们放到新的后缀列表中。在一种情况下,可能没有匹配的左括号(while循环到达堆栈的末尾而没有遇到(,它应该抛出异常。我已经实现了以下代码,但是它似乎没有起作用:

    else if(tok.equals(")")){
      while(stack.peek().equals("(") == false){
        try{
          Operator o = stack.pop();
          nlist.add(o);                
        } catch(EmptyStackException e){
          System.out.println(e.getMessage());
        }
        stack.pop();
      }    

然后在另一个构建GUI并处理输入的文件中,我输入了:

try{
  java.util.List<Token> postfix = ExpressionManager.infixToPostfix(infix);
  // build the expression
  Expression exp = ExpressionManager.buildExpression(postfix);
  // display the results
}catch(ArithmeticException e){
     entryField.setText(e.getMessage())
}

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

在进入try-catch块之前,

stack.peek()抛出EmptyStackException(我假设您期望pop将抛出异常)。

第二个区块没有显示ArithmeticException是如何被抛出的,所以,不确定你在这里期待什么。

答案 1 :(得分:0)

如果你想重新抛出异常,你可以

catch(EmptyStackException e){
    throw new ArithmeticException("empty stack, bad mathematical expression.", e);
}