I made a basic calculator with forms and when wanting to manage the ArithmeticException() by zero
it seems not to enter the catch and execute the sentences that I define for such a case (neither System.out.println, nor JOptionPane.showMessage, nor jtxt_calcu.setText).
-
Equal button (=) that executes the'calc' method
private void btn_igualActionPerformed(java.awt.event.ActionEvent evt) { memoria2=jtxt_calcu.getText(); jtxt_todo.setText(jtxt_todo.getText()+" "+ memoria2); try { jtxt_calcu.setText(this.calc(memoria1, signo, memoria2)); } catch (ArithmeticException e) { jtxt_calcu.setText("Error al dividir por cero"); System.out.println("Error al dividir por cero"); JOptionPane.showMessageDialog(null, "Error al dividir por cero"); } flag=true; }
-
.calc method
public String calc (String memoria1, String signo, String memoria2)throws ArithmeticException { Double resultado=0.0; String respuesta = ""; if (signo.equals("+")){ resultado = Double.parseDouble (memoria1) + Double.parseDouble (memoria2); respuesta = resultado.toString(); } if (signo.equals("-")){ resultado = Double.parseDouble (memoria1) - Double.parseDouble (memoria2); respuesta = resultado.toString(); } if (signo.equals("*")){ resultado = Double.parseDouble (memoria1) * Double.parseDouble (memoria2); respuesta = resultado.toString(); } if (signo.equals("/")){ resultado = Double.parseDouble(memoria1) / Double.parseDouble(memoria2); respuesta = resultado.toString(); } if (respuesta.endsWith(".0")){ respuesta = respuesta.replace(".0","") ; } return respuesta; }
All this is within the Source of the calculator.
The output of the program when divided by ZERO is always'Infinity'in my text field jtxt_calcu
Any ideas on how to make this exception handling work?