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