Excepting-throwing code

A

Alper

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..
 
M

Manish Pandit

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,182
Latest member
BettinaPol

Latest Threads

Top