javaexceptioncalculatorarithmeticexception

How to execute Arithmetic Exception catch block in Java?


This is the code snippet:

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!!");
        }
    }

The JRE is never executing the Arithmetic Exception catch statement, why?

Yes, it is handing it but it not producing the output that I expect it to produce! It is automatically displaying, "Infinity" & "NaN" on my Java application! Thanks!


Solution

  • Yes! Double and float have their own inbuilt values for infinity. There might be some other issues in your code that I'm not aware about.

    Check these edits:

    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+"");
            }
    

    This throw new ArithmeticException(); will force your code to execute the section that you are willing to execute!

    Also, check this link: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html

    Hope this helps!