简体   繁体   English

如何正确引发异常

[英]How to correctly throw an exception

I'm new to java and I'm trying to account for possible errors that might come up in my program. 我是java的新手,我正尝试解决程序中可能出现的错误。 I'm creating a calculator and converting the inputs from infix to postfix to calculate the result. 我正在创建一个计算器,并将输入从中缀转换为后缀以计算结果。 I want to try accounting for mismatched parenthesis in the input, but I'm having trouble. 我想尝试解决输入中括号不匹配的问题,但是遇到了麻烦。 For example, when converting from infix to postfix, when a ) is reached, it will pop numbers from the stack and put them onto the new postfix list. 例如,从缀转换为后缀,当时)到达,它将从栈中弹出的数字,并把它们到新后缀列表。 In one case where there may not be a matching left parenthesis present (the while loop reaches the end of the stack without coming across a ( , it should throw an exception. I've implemented the following code, but it doesn't seem to be working: 在一种情况下,可能没有匹配的左括号(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();
      }    

Then in the other file which constructs the GUI and processes the inputs, I entered: 然后,在构造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())
}

Any suggestions? 有什么建议么?

stack.peek() throws EmptyStackException before you enter inside try-catch block (I assume you expect that pop will throw the exception). 在您进入try-catch块之前, stack.peek()会引发EmptyStackException (我假设您希望pop会引发该异常)。

Second block doesn't show how the ArithmeticException is thrown, so, not sure what you expecting here. 第二个块没有显示ArithmeticException的抛出方式,因此,不确定在此期望什么。

If you want to re-throw an exception you can do 如果要重新引发异常,可以执行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM