Reputation: 13688
I'm using the IDE Netbeans7.3 to develop in Java. There is something strange that I cannot explain to myself, so please, help me to understand.
I declared to classes. The first inherits from Exception
:
public class MyParameterException extends Exception{
public MyParameterException(){
super();
}
public MyParameterException(String message){
super(message);
}
}
and the second inherits from NullPointerException:
public class NullMyParameterException extends NullPointerException{
public NullMyParameterException(){
super();
}
public NullMyParameterException(String message){
super(message);
}
}
Now, when I create a method in a class and I write:
public void test(String s){
if(s==null) throw new NullMyParameterException("The input string is null.");
if(s.trim().isEmpty()) throw new MyParameterException("The input string is empty.");
}
What seems strange to me is that I get the message unreported exception MyParameterException must be caught or declared to be thrown
from the IDE, but nothing is said about the first exception that I could throw in the method.
To my knowledge, the method would expected to be declared as follows:
public void test(String str) throws MyNullParameterException, MyParameterException
but for Netbeans only sufficies:
public void test(String str) throws MyParameterException
Is this:
NullPointerException
are special.Please, let me understand.
Upvotes: 0
Views: 985
Reputation: 4598
Read about runtime exceptions and regular exceptions. http://docs.oracle.com/javase/6/docs/api/java/lang/RuntimeException.html
Runtime exceptions are not checked by the compiler. The IDE uses the compiler to get this information. Will see same output if you compile from command prompt
You should see this too Difference between Unchecked exception or runtime exception
Upvotes: 2
Reputation: 19294
It is normal. When you extends RuntimeException
(NPE in your case) you don't need to declare the method as throwing it.
For checked exceptions (MyParameterException in your case), you must declare the method as throws MyParameterException
in order to throw it.
You can read more about checked vs unchecked exceptions
Upvotes: 1
Reputation: 842
you are not warned about NullPointerException - it is unchecked exception, buy your exceptions should be checked. You should change your program, NullMyParameterException should extends Exception aswell, and you should declare that these exceptions will be thrown in method by:
public void test(String s) throws MyParameterException, NullMyParameterException
Upvotes: 1