I am kind of new to java so pardon this rather simple question, I guess. This method will count how many digits are there on a POSITIVE integer only. So it needs to throw an error to the caller. How do I do so when the input is negative, I throw an error and exit the method without returning anything?
public static int countDigits(int n)
{
if (n<0)
{
System.out.println("Error! Input should be positive");
return -1;
}
int result = 0;
while ((n/10) != 0)
{
result++;
n/=10;
}
return result + 1;
}
You're not throwing an error here; you're displaying an error message and returning a sentinel value of -1
.
If you want to throw an error, you have to use the throw
keyword, followed by an appropriate Exception
.
public static int countDigits(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input should be positive");
}
int result = 0;
while ((n / 10) != 0) {
result++;
n /= 10;
}
return result + 1;
}
The Java Trails on throwing exceptions will provide you with invaluable insights into what different kinds of exceptions there are. Above, IllegalArgumentException
is considered a runtime exception, so something that is calling this method won't be forced to catch its 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