Larry Olson wrote:
But Exception is a catch all, right? It includes both checked and unchecked exceptions. I do understand that it includes RuntimeException. But how can you assume that only RuntimeException will be thrown? I do understand no checking is done for RuntimeException, but again Exception also includes unchecked ones in which compiler has to do the check. How can the compiler assume that only RuntimeException will be thrown if we have Exception in the catch clause? Shouldn't the compiler err on the side of safety?
That is how it is defined in the specification. If you throw an exception, the compiler must check that it is declared or is a runtime exception. Hence, if you try to throw an Exception instance, it is not allowed (assuming that no checked exceptions are declared). On the other hand, if you catch an Exception, it is allowed because it is possible that exception of that type can be thrown.
In other words, all RuntimeExceptions are Exceptions (hence, catch is allowed), but not all Exceptions are RuntimeExceptions (hence, throw is not allowed).
This may initially sound confusing, but it makes sense. Catching the superclass Exception, or the superclass Throwable, for default (last) cases, is pretty common.
Larry Olson wrote:
Also look at the case of where you extend the Exception class to create a new Exception. But look at how differently the compiler now treats this exception It assumes that it is a checked exception, though logically Exception includes RuntimeException, right? .
No. When you inherit from the Exception class, you are not inheriting from RuntimeException -- this the compiler can easily confirm.
Henry