Search code examples
javaexceptiontry-catchthrow

When should I announce "throws", and when not?


I noticed that both of these, for example, are working:

public void func(int a) throws IllegalArgumentException {
    if(a < 0) 
        throw new IllegalArgumentException("a should be greater than 0.");
}

public void func(int a) {
    if(a < 0) 
        throw new IllegalArgumentException("a should be greater than 0.");
}

It makes me to ask:

When should I announce throws anException, and when not, and just throw it without declare about it?


Solution

  • Checked exceptions must be always written in the method signature that it throws.

    If the exception extend RuntimeException, you don't have to write throws in the method name, but it's highly recommended since it's clearer and it'll be mentioned in the documentation of the method.

    /**
     * @throws This won't appear if you don't write `throws` and this might
     * mislead the programmer.
     */
    public void func(int a) throws IllegalArgumentException {
        if(a < 0) 
            throw new IllegalArgumentException("a should be greater than 0.");
    }