Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception if method arguments are invalid

Tags:

java

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;
    }
like image 769
Gavin Avatar asked Nov 09 '22 05:11

Gavin


1 Answers

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.

like image 61
Makoto Avatar answered Nov 14 '22 21:11

Makoto