I find Java’s exception hierarchy confusing. Throwable is divided into Error and Exception, and RuntimeException inherits from Exception.
-
Erroris an unchecked exception. Why doesn’tErrorinherit fromRuntimeExceptionthen? -
Exceptionis a checked exception.RuntimeExceptionis an unchecked exception, yet it inherits fromException. Doesn’t this violate the Liskov-Substitution-Principle?
Wouldn’t it make more sense if Throwable were divided into Exception (checked) and RuntimeException (unchecked), and Error would inherit from RuntimeExeption?
A
Throwableis anything that can be used to unwind the call stack. This should include some VM level fault (flagged by an Error) and something application specific (flagged by an Exception)Simply because Errors are not Exceptions. There wouldn’t be any point in actually “catching” an Error. For eg. What would you do after catching an
OutOfMemoryError. Errors are meant to flag something seriously happened at the VM level which is not necessarily handle-able by the programmerNot really. What the implementors were trying to say was that Exceptions MUST always be checked. Your code will be cleaner if all your methods declare what sort of application/library Exceptions they throw. RuntimeExceptions should only be thrown in case of more general / dynamic situations such as a
NullPointerExceptionwhere the developer might not have coded for the case but is a serious bug which is not exactly something mentioned in the application spec.