Trying to figure out the best place to put a try catch statement when a recursive call is placed. The factorial computation is done with long datatype. Expecting an exception to be thrown when the factorial becomes too huge to fit into a long variable.
However the code is showing factorial = 0 whenever it’s too large. No exception is being thrown. So is there a problem with the try-catch placement or does putting over-large numbers throw no exception?
class Fact
{
static long fact(long n)
{
if(n==1)
return 1;
return n*fact(n-1);
}
public static void main(String args[])
{
try{
long f = fact(555);
System.out.println("Factorial = "+f);
}
catch(Exception e){
System.out.println("Exception = "+e);
}
}
}
Integer overflow doesn’t throw any exceptions in Java. Integer divide by zero throws
ArithmeticException, but not overflow.The question has now morphed into “Why does this return zero?” And the answer is that it’s just a coincidence. If you modify the function like this:
and then look at the output, you get (I deleted some lines in the middle and at the end):
and then once it’s hit zero, it’s zero ever after. After bouncing around and overflowing a few times, your product just accidentally hits a number with 0s in the least significant 64 bits. Strange, but true.