Wednesday, May 29, 2019

Java 'throws' clause not needed when throwing a new NPE? and why does adding "throws Exception" give compilation errors?




I got curious about the 'throws' clause and wrote the following piece of code (I use Eclipse with Java7). Originally I had started with only blocks 1 and 5 (expecting a compilation error, which did not occur...) and then this led me to writing the other blocks.



// 1
public void throwNPE() {

throw new NullPointerException();
}

// 2
public void throwNPEWithGenericClause() throws Exception {
throw new NullPointerException();
}

// 3
public void throwNPEWithNPEClause() throws NullPointerException {

throw new NullPointerException();
}

// 4
public void throwNPEWithIAEClause() throws IllegalArgumentException {
throw new NullPointerException();
}

// 5
public void callThrowNPE() {

throwNPE();
}

// 6
public void callThrowNPEWithGenericClause() {
throwNPEWithGenericClause(); // COMPILATION ERROR
}

// 7
public void callThrowNPEWithNPEClause() {

throwNPEWithNPEClause();
}

// 8
public void callThrowNPEWithIAEClause() {
throwNPEWithIAEClause();
}


To be honest I would have expected:




(a) a compilation error in 1. (unhandled exception? shouldn't my method notify any 'subsequent caller' that this is going to throw some kind of exception?)



(b) some kind of problem in 4. (possibly a compilation error? I'm throwing a NPE while the clause says IAE)



(c) compilation errors in 5. 6. 7. and 8. (unhandled exceptions? I'm omitting the 'throws' clause)



(d) perhaps someone could also tell me why 6. is the only one where I got the compilation error...


Answer



RuntimeException is unchecked, so compiler does not warn when you throw a exceptions subclass of RuntimeException. If you need compiler to warn you, then you should use Exception or its subclasses.




1) NullPointerException extends RuntimeException
so compiler does not give any error.



2) Even though your method throws NullPointerException, since you marked the method with throws Exception, compiler warns you to catch it in it's callers.



3) Same as 1st answer



4) Same as 1st answer
IllegalArgumentException extends RuntimeException




5) throwNPE does not throw anything at all.



6) Eventhough you throw a NullPointerException (RuntimeException) within throwNPEWithGenericClause, since you mark the method as checked exception, compiler does not allow.



7, 8) Same as 1st answer. Both runtime exceptions, no need to check.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...