如果方法参数无效则抛出异常

Gav*_*vin 7 java

我对java有点陌生,所以请原谅这个相当简单的问题,我想。此方法将仅计算正整数上有多少位。所以它需要向调用者抛出一个错误。当输入为负数时,我会抛出错误并退出方法而不返回任何内容,该怎么办?

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;
    }
Run Code Online (Sandbox Code Playgroud)

Mak*_*oto 6

你不会在这里抛出错误;您正在显示错误消息并返回哨兵值-1

如果您想引发错误,则必须使用throw关键字,后跟适当的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;
}
Run Code Online (Sandbox Code Playgroud)

关于抛出异常的Java Trails将为您提供有关异常类型的宝贵见解。上面的内容IllegalArgumentException被认为是运行时异常,因此调用此方法的内容不会被迫捕获其异常。