Sitemap
Rupam Thakre

Rupam Thakre

Java Developer, SpringBoot Developer, Backend Development, Microservices Rest API Development, Angular, Apache Camel, Apache Kafka

Java : Errors

Understanding Errors in Java

5 min readFeb 6, 2025

--

In Java, errors represent serious issues that are typically outside the control of the program and usually cannot be handled. Errors differ from exceptions in that they are typically not recoverable, and handling them is generally not advisable. Java provides a robust exception-handling mechanism to deal with exceptions, but errors, on the other hand, signal severe problems that usually cause the program to terminate.

In this blog, we will explore the concept of errors in Java, differentiate them from exceptions, discuss common types of errors, and provide examples to understand how they affect Java applications.

Table of Contents

  1. What is an Error in Java?
  2. Errors vs Exceptions
  3. Types of Errors in Java
  4. How to Handle Errors in Java
  5. Common Examples of Errors
  6. Best Practices for Avoiding Errors
  7. Conclusion

What is an Error in Java?

In Java, an error is a subclass of Throwable, which is the superclass for both exceptions and errors. Errors in Java typically indicate severe conditions that a program cannot recover from. These are issues related to the environment in which the application is running, such as memory exhaustion or hardware failure.

Errors are used by the Java runtime environment to indicate serious problems. Unlike exceptions, errors are usually not expected to be handled by the programmer. When an error occurs, the program generally cannot continue execution, and the Java Virtual Machine (JVM) terminates the program.

Key Characteristics of Errors:

  • Not Recoverable: Errors typically represent conditions that cannot be handled programmatically.
  • Severe Issues: Errors usually indicate serious problems with the JVM, system, or hardware.
  • Infrequent Occurrence: Errors are less common than exceptions but more severe.

Errors vs Exceptions

The main distinction between errors and exceptions in Java is how they are handled and what they represent:

Features Errors Exceptions

  1. Definition

Errors : Represents severe conditions that are usually beyond the program’s control (e.g., system failure).

Exceptions : Represents conditions that can be caught and handled to allow the program to continue.

2. Recoverability

Errors : Generally not recoverable by the program.

Exceptions : Typically recoverable with exception handling (try-catch).

3. Cause

Errors: Caused by external factors like hardware issues, JVM bugs, or resource limitations.

Exceptions : Caused by issues like invalid user input, file not found, etc.

4. Class Hierarchy

Errors : Direct subclass of Throwable, but not Exception.

Exceptions : A subclass of Throwable and a subclass of Exception.

5. Examples

Errors : OutOfMemoryError, StackOverflowError.

Exceptions : IOException, NullPointerException, FileNotFoundException.

6. Handling

Errors : Typically not handled; the program usually terminates.

Get Rupam Thakre’s stories in your inbox

Join Medium for free to get updates from this writer.

Exceptions : Can be caught and handled using try-catch blocks.

Types of Errors in Java

Java provides several types of errors that represent different kinds of critical problems. These errors extend the Error class, which is a subclass of Throwable. Some of the common types of errors are:

1. OutOfMemoryError

The OutOfMemoryError occurs when the Java Virtual Machine (JVM) runs out of memory to allocate for new objects. This error usually happens when the program consumes too much memory, often due to memory leaks or creating excessive objects.

Example:

public class OutOfMemoryErrorExample {
public static void main(String[] args) {
try {
// Creating a large number of objects in memory
while (true) {
String[] largeArray = new String[1000000]; // Simulate a memory exhaustion
}
} catch (OutOfMemoryError e) {
System.out.println("Error: Out of memory!");
}
}
}

Explanation:

  • The program continuously creates large arrays inside a loop, which eventually leads to the JVM running out of memory.
  • The OutOfMemoryError is thrown when there is no more memory available for allocation.

Output:

Error: Out of memory!

2. StackOverflowError

The StackOverflowError occurs when the stack, which is used to store method calls and local variables, overflows. This often happens in recursive methods where the recursion depth exceeds the available stack space.

Example:

public class StackOverflowErrorExample {
public static void recursiveMethod() {
recursiveMethod(); // This causes infinite recursion
}
public static void main(String[] args) {
try {
recursiveMethod(); // Start the recursive method
} catch (StackOverflowError e) {
System.out.println("Error: Stack overflow due to infinite recursion.");
}
}
}

Explanation:

  • In this example, the recursiveMethod calls itself indefinitely, leading to a stack overflow.
  • The JVM detects this and throws a StackOverflowError when the recursion exceeds the available stack space.

Output:

Error: Stack overflow due to infinite recursion.

3. VirtualMachineError

A VirtualMachineError indicates a serious problem with the JVM itself, such as an internal failure. These are rare and typically not recoverable.

Example:

public class VirtualMachineErrorExample {
public static void main(String[] args) {
try {
// Simulate a JVM issue (not something you can easily replicate)
throw new VirtualMachineError("Simulated virtual machine error.");
} catch (VirtualMachineError e) {
System.out.println("Error: Virtual machine failure: " + e.getMessage());
}
}
}

Explanation:

  • This example demonstrates the throwing of a VirtualMachineError directly, though in real scenarios, this type of error is usually thrown by the JVM under extreme conditions.

Output:

Error: Virtual machine failure: Simulated virtual machine error.

How to Handle Errors in Java

In Java, errors are generally not handled explicitly because they indicate serious problems that cannot be recovered from. Unlike exceptions, which can be caught and handled using try-catch blocks, errors are typically left unhandled, and the program is allowed to terminate.

However, there are situations where you may want to catch and log errors to provide information about the issue before the program terminates.

Example: Catching an Error (Not Recommended)

public class ErrorHandlingExample {
public static void main(String[] args) {
try {
// Simulate an OutOfMemoryError (unsafe)
String[] largeArray = new String[10000000]; // May throw OutOfMemoryError
} catch (OutOfMemoryError e) {
System.out.println("Caught error: " + e.getMessage());
// Typically, we log the error and allow the program to terminate
}
}
}

Explanation:

  • In the above example, we try to catch an OutOfMemoryError. While catching this error is possible, it is not recommended because it usually signifies a problem that cannot be fixed by the program.
  • Instead of attempting recovery, it’s best to log the error and allow the JVM to exit.

Output:

Caught error: Java heap space

Common Examples of Errors

  1. OutOfMemoryError: Caused by memory exhaustion, usually due to excessive object creation or memory leaks.
  2. StackOverflowError: Caused by excessive recursion or deep method call stacks.
  3. VirtualMachineError: A critical error related to the JVM itself, often indicating a failure in the JVM’s runtime environment.

Best Practices for Avoiding Errors

While errors are often beyond your control, here are some practices that can help reduce the likelihood of errors:

  1. Avoid Deep Recursion: If possible, replace recursive algorithms with iterative ones to avoid stack overflows.
  2. Memory Management: Be mindful of memory usage. Use tools to profile memory consumption and detect memory leaks.
  3. Optimize the JVM: Use the correct JVM options and configurations (e.g., adjusting heap size, garbage collection settings) to avoid OutOfMemoryError.
  4. Graceful Shutdown: If errors are unavoidable, ensure the application performs proper cleanup, such as closing files, releasing resources, and logging error details.

Conclusion

In Java, errors represent serious, often catastrophic issues that are not recoverable by the program. Errors typically indicate environmental issues like JVM failures, memory exhaustion, or stack overflow. While exceptions are handled by the programmer, errors are not intended to be caught and handled in the same way. The best practice is to prevent them through careful coding, but if they occur, logging and allowing the program to terminate gracefully is typically the best approach.

Understanding errors and their differences from exceptions helps ensure your Java applications are more reliable and resilient in the face of unexpected conditions.

--

--

Rupam Thakre
Rupam Thakre

Java Developer, SpringBoot Developer, Backend Development, Microservices Rest API Development, Angular, Apache Camel, Apache Kafka