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?
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.");
}
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.
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.
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