I have a question about exceptions..
I have this method;
public void calculate(int x) throws IllegalArgumentException {
if(x > 10) throw new IllegalArgumentException("x must be bigger than
10);
//some code here
}
and this one;
public calculate(int x) {
if(x > 10) throw new IllegalArgumentException("x must be bigger than
10);
//some code here
}
What's the purpose of putting "throws IllegalArgumentException" in the
method defination? I mean I run both of them, I couldn't see any
difference.. both gives the same error when I enter argument smaller
than 10. I know it is declaring to the method (which calls calculate())
that it will throw exception.. but it also runs without it.. so why
would I bother putting it?
Thanks for ur answers..
Manish Pandit - 12 Oct 2006 01:55 GMT
Hi,
Assuming you are referring to java.lang.IllegalArgumentException, it
will not make a difference because IllegalArgumentException is an
unchecked exception (it extends java.lang.RuntimeException). You do not
need to declare unchecked exceptions in the method signature per the
standard practices. They do need to be mentioned in the javadocs
though, so that the consumers know what to expect.
This exception falls under the same category as NullPointerException -
you can specify 'throws NullPointerException' in your method signature,
but the compiler will not force the consumers to handle it. Similarly,
you can throw NullPointerException at will from your code, the compiler
will not force you to declare it.
-cheers,
Manish