Reputation: 45
In this code a division method is implemented, so i want to handle 3 cases where division is undefined using try catch and throws, but it gives me an error message that the division method must return float . package calculator3;
//Class implements interface public class implementation implements calc {
//Add function
public int add(int x, int y) {
int ans1 = x + y ;
return ans1 ;
}
//Divide function
public float divide(int x, int y) throws RuntimeException{
try {
if(y == Double.POSITIVE_INFINITY || y == Double.NEGATIVE_INFINITY || y == 0 ) {
throw new ArithmeticException("invalid_division");
}
else {
return x / y ;
}
}catch (ArithmeticException invalid_division ) {
System.out.println("invalid_division");
}
}
}
Upvotes: 0
Views: 473
Reputation: 2821
Your divide
return type is float
.
An int will never equal Double.POSITIVE_INFINITY
or Double.NEGATIVE_INFINITY
because those are not in their range of possible values.
The function will not throw an error if it is caught.
Taking above 3 points:
//divide
public float divide(int x, int y) throws ArithmeticException{
if (y == 0) throw new ArithmeticException("invalid_division");
return (float)x / y; // cast x to float so a float will result
}
Upvotes: 1
Reputation: 849
Your not actually throwing the exception once catching it so the compiler will complain that your missing a return in your divide()
method.
add:
throw e;
to your catch clause
Upvotes: 0