Given the program following:
class FirstException extends Exception {}
class SecondException extends Exception {}
class RethrowException {
public void rethrowMethod() throws FirstException, SecondException {
boolean flag = true;
try {
if(flag)
throw new FirstException();
else
throw new SecondException();
}
catch(Exception ex) {
throw ex; // does not compile "Unhandled exception type Exception"
}
}
}
This error just happens with Java SE 6 (or prior versions) because firstly, when we build the "catch" block (catch(Exception ex)), the exception object, specified by ex, has the type of FirstException (or SecondException). But, when ex is re-thrown (throw ex), the Java compiler performs 3 tasks as follows:
- Release "ex" to system.
- Initialization new exception object, "ex" that has the type of Exception
- Throw "ex" - that is instance of Exception, right now, not instance of
FirstException(orSecondException)
Thus, in the Java SE 6, we cannot use "more precisely rethrow exception" because the reason following. However, in the Java SE 7 (or later), we can do that, because when we re-throw ex, the runtime system does not release and initialize new object ex. It will check (find) where ex1 come from (the try block above), and so know thatexis an instance ofFirstExceptionorSecondException`.
My explanation above is correct or not?