Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I announce "throws", and when not? [duplicate]

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?

like image 547
Billie Avatar asked Oct 22 '13 11:10

Billie


3 Answers

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.");
}
like image 91
Maroun Avatar answered Sep 19 '22 23:09

Maroun


The beauty with Throws is that the Exception converts into Checked Exception thus every time any developer will try to use the first approach he will be warned to place a try-catch block before calling the method which has Throws in its Signature.

like image 37
Pawan Shukla Avatar answered Sep 19 '22 23:09

Pawan Shukla


From the JLS section 11.2:

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.6) or constructor (§8.8.5) must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

so briefly, you need the throws statement if an exception is checked. If you have an Exception, and it's not a subclass of RuntimeException, then it's checked.

IllegalArgumentException is a subclass of RuntimeException, and so it's unchecked, and you shouldn't need to declare it in a throws statement. This is true of most exceptions like this (IllegalArgumentException, NullPtrException etc.) since you can't reasonably be expected to handle these easily.

like image 29
Brian Agnew Avatar answered Sep 17 '22 23:09

Brian Agnew