-1

这是代码片段:

public void actionPerformed(ActionEvent e){
        int i1,i2;

        try{
            if(e.getSource()==b1){
            .
            .
            .

            else if(e.getSource()==b4){
                double i1,i2;
                i1=Integer.parseInt(t1.getText());
                i2=Integer.parseInt(t2.getText());
                i1=i1/i2;
                l7.setText(i1+"");
            }
            else if(e.getSource()==b5){
                i1=Integer.parseInt(t1.getText());
                i2=Integer.parseInt(t2.getText());
                i1=i1%i2;
                l7.setText(i1+"");
            }
        }
        catch(ArithmeticException ex2){
            l7.setText("Debugging?");
            JOptionPane.showMessageDialog(null,"Divide by zero exception!!");
            //*WHY THIS SECTION IS NEVER BEING EXECUTED AFTER PERFORMING A DIVIDE BY ZERO i.e. ARITHMETIC EXCEPTION!*
        }
        catch(Exception ex){
            JOptionPane.showMessageDialog(null,"Enter Values First!!");
        }
    }

JRE 从不执行算术异常捕获语句,为什么?

是的,它正在处理它,但它没有产生我期望它产生的输出!它会在我的 Java 应用程序上自动显示“Infinity”和“NaN”!谢谢!

4

2 回答 2

0

检查这些代码行:

        } else if (e.getSource() == b4) {
            double i1, i2; // Comment this line to make it work like you need
            i1 = Integer.parseInt(t1.getText());
            i2 = Integer.parseInt(t2.getText());
            i1 = i1 / i2;
            l7.setText(i1 + "");
        }

您已将 i1 和 i2 重新声明为双精度。Double 类型定义了InfinityNaN的内置值。这就是您的代码没有执行 ArithmeticException catch 块的原因。

只需注释该double i1, i2;行以使其按您的需要工作。

更新

如果要显示错误消息,只需勾选:

        } else if (e.getSource() == b4) {
            double i1, i2;
            i1 = Integer.parseInt(t1.getText());
            i2 = Integer.parseInt(t2.getText());
            if(i2==0){
                throw new ArithmeticException("Cannot divide by zero");
            }
            i1 = i1 / i2;
            l7.setText(i1 + "");
        }

希望这可以帮助!

于 2017-02-14T10:30:15.563 回答
0

是的!Double 和 float 有自己的内置无穷大值。您的代码中可能还有其他一些我不知道的问题。

检查这些编辑:

else if(e.getSource()==b4){
            double i1,i2;
            i1= Integer.parseInt(t1.getText());
            i2= Integer.parseInt(t2.getText());
            if(i1!=0 && i2 == 0){
                throw new ArithmeticException();
            }
            else if(i2 == 0 && i1 == 0) {
                throw new ArithmeticException();
            }
            i1= i1/i2;
            l7.setText(i1+"");
        }

throw new ArithmeticException();将强制您的代码执行您愿意执行的部分!

另外,请查看此链接: https ://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html

希望这可以帮助!

于 2017-02-14T11:31:57.613 回答