Detect division by zero

From Rosetta Code
Revision as of 19:06, 17 February 2008 by rosettacode>Mwn3d (Created task with Java)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Detect division by zero
You are encouraged to solve this task according to the task description, using any language you may know.

Write a function to detect a divide by zero error without checking if the denominator is zero.

Java

Two ways to accomplish this task are presented here. They each return true if there is a division by zero or if Double.POSITIVE_INFINITY is used as a numerator.

One way to do this check in Java is to use the isInfinite function from the Double class:

public static boolean infinity(double numer, double denom){
	return Double.isInfinite(numer/denom);
}

Another way is to use the ArithmeticException as a check (which is not preferred because it expects an exception):

public static boolean except(double numer, double denom){
	try{
		int dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math
		return false;
	}catch(ArithmeticException e){return true;}
}