Java.Core.What is an Error?

What is an Error in Java?

In Java, an Error is a serious, unrecoverable issue that occurs at the JVM (Java Virtual Machine) level. It is not meant to be caught or handled because it usually indicates a fatal problem that the application cannot recover from.


1. Characteristics of Errors

Extends java.lang.Error (not Exception).
Indicates serious system-level failures (e.g., memory leaks, JVM crashes).
Should not be caught (handling them is usually pointless).
Mostly caused by hardware, JVM, or system failures, not by programming mistakes.


2. Error Class Hierarchy

java.lang.Throwable
├── java.lang.Exception (Recoverable)
│   ├── CheckedException
│   ├── RuntimeException (Unchecked)
└── java.lang.Error (Non-Recoverable)
    ├── VirtualMachineError
    │   ├── OutOfMemoryError
    │   ├── StackOverflowError
    ├── AssertionError
    ├── LinkageError
        ├── ClassNotFoundError
        ├── NoClassDefFoundError

Common Types of Errors

Error TypeWhen It Occurs
OutOfMemoryErrorJVM runs out of heap memory
StackOverflowErrorInfinite recursion fills the stack
VirtualMachineErrorJVM crashes due to critical failures
AssertionErrorFailed assert statements
NoClassDefFoundErrorA class was present at compile-time but missing at runtime
ClassFormatErrorClass file format is incorrect

4. Examples of Errors

1️⃣ OutOfMemoryError

Occurs when JVM runs out of heap memory.

import java.util.*;

public class OutOfMemoryExample {
    public static void main(String[] args) {
        List<int[]> list = new ArrayList<>();
        while (true) {
            list.add(new int[1_000_000]); // Allocating large memory continuously
        }
    }
}

🛑 Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Prevention: Increase JVM heap size (-Xmx flag) or optimize memory usage.

2️⃣ StackOverflowError

Occurs due to infinite recursion.

public class StackOverflowExample {
    public static void recursiveMethod() {
        recursiveMethod(); // Infinite recursion
    }

    public static void main(String[] args) {
        recursiveMethod();
    }
}


🛑 Output:

Exception in thread "main" java.lang.StackOverflowError

Prevention: Use base conditions to stop recursion.


3️⃣ NoClassDefFoundError

Occurs when a class was available during compilation but missing at runtime.

// Suppose `MyClass` was compiled but deleted before execution
public class NoClassDefFoundExample {
    public static void main(String[] args) {
        MyClass obj = new MyClass(); // If MyClass.class is missing, NoClassDefFoundError occurs
    }
}

🛑 Output:

Exception in thread "main" java.lang.NoClassDefFoundError: MyClass

Prevention: Ensure required .class files are available.

5. Can We Catch Errors?

While it’s technically possible to catch an Error, it is not recommended because:

  • Errors indicate serious failures that should not be handled.
  • Handling them may cause undefined behavior.
  • Most errors should lead to program termination.

Example: Catching an Error (Not Recommended)

public class CatchErrorExample {
    public static void main(String[] args) {
        try {
            int[] arr = new int[Integer.MAX_VALUE]; // Causes OutOfMemoryError
        } catch (Error e) { // Not recommended
            System.out.println("Caught Error: " + e);
        }
    }
}

🚨 Best Practice: Instead of catching an Error, prevent it by writing efficient code.


6. Difference Between Error and Exception

FeatureErrorException
Extendsjava.lang.Errorjava.lang.Exception
Recoverable?❌ No✅ Yes (with try-catch)
Caused by?JVM issues (memory, stack, linking)Programming mistakes or external issues
Should be handled?❌ No✅ Yes
ExamplesOutOfMemoryError, StackOverflowErrorIOException, SQLException

7. Final Thoughts

Errors (java.lang.Error) are fatal and should not be handled.
Common errors include OutOfMemoryError, StackOverflowError, and NoClassDefFoundError.
Instead of handling errors, focus on preventing them with better coding practices.

This entry was posted in Без рубрики. Bookmark the permalink.