Question

In both my java an C++ programs, I have put a simple try/catch block to catch a divide by zero exception. Instead of addressing the problem, the program says the answer is infinity. Why is this happening?

Java (C++ almost exactly like this):

import java.util.Scanner;
import java.lang.ArithmeticException;
public class Expiriment {



    static double a;
    static double b;


    public static void main (String [] args){

        try {

        Scanner input = new Scanner (System.in);
            System.out.println("Enter first Number");
            a = input.nextInt();
            System.out.println("Enter 2nd number");
            b = input.nextInt();
            System.out.println("Answer is:"+ a/b);  

        }
        catch (ArithmeticException e) {
            double f = 0;
            System.err.println (e+" "+"Cannot perform operation.");
            System.out.println("Answer is:" + f);
        }


        }

    }
Was it helpful?

Solution

Do not compare Java's try/catch with C++'s try/catch. Division by zero in a C++ program is not a C++ exception.

Please see here:

Catching exception: divide by zero

OTHER TIPS

IEEE754 floating point division is defined to return infinity for nonzero a and 0 b, or NaN if you divide 0/0. Hence, you get such a result in your print statement.

Wikipedia:

Division by zero (an operation on finite operands gives an exact infinite result, e.g., 1/0or log(0)) (returns ±infinity by default).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top