public double get_volume(int a){
try{
if (a < 0) {
// this gets caught in the catch block
throw new IllegalArgumentException("Only Positive Numbers & no Letters Please!");
}
return a*a*a;
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
If this function receives a negative value, it will throw an exception to say that it is not allowed. Else, it will proceed to calculate the volume. Somehow I still have to return some value but is it really needed? How do i write this code correctly?
If you are catching the exception inside the method without throwing any exception to the caller (as you currently do), you must return some default value in your catch block.
It would probably make more sense not to catch the exception within the method, which will allow you not to return anything when the exception is thrown. It will also inform the caller they passed invalid input.
public double get_volume(int a)
{
if (a < 0) {
throw new IllegalArgumentException("Only Positive Numbers & no Letters Please!");
}
return a*a*a;
}
Now it's the responsibility of the caller to handle the exception.
Note that since IllegalArgumentException
is an unchecked exception (since it is a sub-class of RuntimeException
), you don't need to declare that your method throws
this exception. It would be helpful, though, to describe in the Javadoc when you are throwing this exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With