Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need Error class?

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?

like image 319
Anirudha Avatar asked Nov 29 '22 16:11

Anirudha


1 Answers

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:

  • you must declare a checked exception in your 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;
  • you may declare an unchecked exception in your 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);
  • etc etc.

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.

like image 154
fge Avatar answered Dec 04 '22 21:12

fge