What are Errors in Java?

Errors in java are abnormal conditions that occur during the execution of the program and can not be resolved by normal conditions. Since these are abnormal conditions, Errors in java are referred to as unchecked exceptions.

Errors cannot be solved by any handling techniques like using try-catch. So, when an error occurs, it causes termination of the program.

Some examples of Errors in java are:

  1. OutOfMemoryError: If there is not sufficient space to allocate an object in the Java heap we will get OutOfMemoryError. In this case, The garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further.
  1. StackOverflowError: When the application’s stack gets exhausted due to deep recursion, we will get StackOverflowError in java.
  1. ClassFormatError: When JVM tries to read a class file and find that the file is malformed or cannot be interpreted as a class file then we will get ClassFormatError in java.
  1. NoClassDefFoundError: If a class loader instance or JVM tries to load in the class definition and does not find any class definition then we will get NoClassDefFoundError in java.

Let’s check an example for NoClassDefFoundError:

In the following example, we have the main class Test, which is creating an object for MyClass.

Step 1: Save the above program in one file Test.java

Java Code
class Test {
public static void main(String args[]) {
MyClass myClass = new MyClass();
}
}

class MyClass {

}

Step 2: Compile the above file as javac Test.java as shown in the following image.

Once Compilation is successful two .class files will be created Test.class and MyClass.java as shown.

Step 3: Delete the generated MyClass.class file from the location.

Step 4: Once the file is deleted run the Test class as shown below we will get NoClassDefFoundError.

Note that after that file is deleted we did not recompile the Test.java file we directly run the Test class.

Following are the differences between Exception and Errors in java.:

Exception in javaError in java
Can be handled using throw or try-catchCan not be handled
Defined in java.lang.Exception packageDefined in java.lang.Error package
Can be checked and uncheckedError are unchecked
Caused because of mistakes in program implementationDoes not caused by mistakes in program. This is mostly environment specific.

-A blog by Shwetali Khambe

Related Posts