这是代码段:
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永远不会执行Arithmetic Exception catch语句,为什么?
是的,它正在处理它,但它没有产生我期望它产生的输出! 它会自动显示," Infinity" &安培; " NaN的"在我的Java应用程序上! 谢谢!
答案 0 :(得分: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类型定义Infinity和NaN的内置值。这就是你的代码没有执行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 + "");
}
希望这有帮助!
答案 1 :(得分: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
希望这有帮助!