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:
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);
}
}
}
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:
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.
Division by zero (an operation on finite operands gives an exact infinite result, e.g.,
1/0
orlog(0)
) (returns±infinity
by default).