I am trying to understand the Error
class in Java.
I have a good understanding of the Exception
class, but can't find examples of code for the Error
class. I've tried searching the web and also the java.sun website, but I'm not finding anything useful to help me understand this better.
How do I use the Error
class in programs and where do we have to use that?
The most common causes of runtime errors in Java are: Dividing a number by zero. Accessing an element in an array that is out of range. Attempting to store an incompatible type value to a collection.
Both exceptions and errors are the subclasses of a throwable class. The error implies a problem that mostly arises due to the shortage of system resources. On the other hand, the exceptions occur during runtime and compile time.
You don't use Error
in your code.
An Error
is a specific kind of Throwable
, just as Exception
is.
Throwable
is the base class that defines everything that can be thrown.Exception
is the common case. It is about problems that occur during the execution of your program.
RuntimeException
is a special case: it's unchecked (i.e. it need not be declared by a method and the compiler doesn't force you to catch it).Error
is the "rare" case: it signifies problems that are outside the control of the usual application: JVM errors, out of memory, problems verifying bytecode: these are things that you should not handle because if they occur things are already so bad that your code is unlikely to be able to handle it sanely.You should not attempt to correct the situation that resulted in an Error
. You might want to catch it in order to log it and then rethrow it (see the JavaDoc of ThreadDeath
for an example on why you need to rethrow it (thanks to @krock for the heads-up)).
There is no other reason to throw any Error
(i.e. don't create an Error
on your own and throw it, if you think you want to do that, use an Exception
or a RuntimeException
instead).
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