Reputation: 494
I'm new to java and I'm trying to account for possible errors that might come up in my program. 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:
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:
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?
Upvotes: 0
Views: 198
Reputation: 28951
stack.peek()
throws EmptyStackException
before you enter inside try-catch block (I assume you expect that pop
will throw the exception).
Second block doesn't show how the ArithmeticException
is thrown, so, not sure what you expecting here.
Upvotes: 2
Reputation: 721
If you want to re-throw an exception you can do
catch(EmptyStackException e){
throw new ArithmeticException("empty stack, bad mathematical expression.", e);
}
Upvotes: 0