How is the below one correct? I expected compiler to tell me to use throws Exception
or throws RuntimeException
public void method1() throws NullPointerException {
throw new RuntimeException();
}
why I think its not correct -> Bcoz a NPE is a RTE, but a RTE is not a NPE
How is this correct? I expected compiler to tell me to use throws Exception
or throws RuntimeException
or throws NumberFormatException
public void method2() throws NullPointerException {
throw new NumberFormatException();
}
public void method3() throws Exception { // this is fine, as expected
throw new RuntimeException();
}
public void method4() throws RuntimeException { // this is fine, as expected
throw new NullPointerException();
}
public void method5() throws Exception { // this is fine, as expected
throw new NullPointerException();
}
Answer:
for RTE even if u don't add throws
clause to the method, compiler won't say anything
public void method6() { // no compile time errors!!
throw new NullPointerException();
}
But when we explicitly say that 'throw new NullPointerException();
' , why compiler ignores it?
It is same as 'throw new SQLException()
;'
It is not thrown on runtime say some object was evaluated to null, and invoked an action on that null object.
Normally a function must declare all the exceptions that it can throw, but RTE's is bypassing it!
RTE's are unchecked exceptions. But when you say throw new RTE, still unchecked?!
Question - Isn't this a flaw? or please correct me in understanding why is it like that
- Update:
Please note that this question is not about difference between checked exception and unchecked exception. The question is not about difference between any type of exception or error.
The question is why an explicitly marked RunTimeException is not handled, or left without forcing the compiler to handle it.
eg:
public void methodA() { // methodA is not forced to handle the exception.
methodB();
}
public void methodB() throws RuntimeException {
}