1

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


        }

    }
harsh
  • 85
  • 1
  • 3
  • 9
  • 1
    Because `a/0` is infinity in floating-point arithemtic (assuming `a != 0`). If you want to prevent divide-by-zero, just directly test the value of `b` before you do the division. – Oliver Charlesworth Apr 20 '14 at 19:50

2 Answers2

2

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).

nanofarad
  • 40,330
  • 4
  • 86
  • 117
2

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

Community
  • 1
  • 1
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45