We have Throwable
class which is the base class for Error
class (for unrecoverable errors) and Exception
class(for recoverable errors)
So,
1> we can throw
an object that implement error
class.(Although it doesn't make sense to implement Error
class because we have Exception
class to do the same thing..)
2> Java doesn't recommend to catch Error
object..
So what is the need of Error
object then? Cant the compiler implement it internally? Isn't it a mistake?
Technically, the distinction is not really made between "unrecoverable error" and "recoverable error", but between checked exceptions and unchecked exceptions. Java does distinguish between them as follows:
throws
clause; if using a method which throws a checked exception in a try
block, you must either catch
said exception or add this exception to your method's throws
clause;throws
clause (not recommended); if using a method which throws an unchecked exception in a try
block, you may catch
that exception or add this exception to your method's throws
clause (not recommended either).What is certainly not recommended, unless you really know what you are doing, is to "swallow" any kind of unchecked exception (ie, catch
it with an empty block).
Exception
is the base checked exception class; Error
and RuntimeException
are both unchecked exceptions, and so are all their subclasses. You will note that all three classes extend Throwable
, and the javadoc for Throwable
states that:
For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.
Classical examples of (in)famous unchecked exceptions:
OutOfMemoryError
(extends Error
);StackOverflowError
(extends Error
);NullPointerException
(extends RuntimeException
);IllegalArgumentException
(extends RuntimeException
);The only real difference between Error
and RuntimeException
is their estimated severity level, and is a "semantic" difference, not a technical difference: ultimately, both behave the same. Some IDEs (Intellij IDEA comes to mind) will also yell at you if you catch an Error
but do not rethrow it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With