Java : OutOfMemoryError with Examples

OutOfMemoryError (Java SE 21 & JDK 21) with Examples.
You will find code examples on most OutOfMemoryError methods.


Summary

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

Class diagram

try {
    final var array = new int[1000000000];
} catch (OutOfMemoryError e) {
    System.out.println(e);
}

// Result
// ↓
//java.lang.OutOfMemoryError: Java heap space

Constructors

OutOfMemoryError ()

Constructs an OutOfMemoryError with no detail message.

final var e = new OutOfMemoryError();
System.out.println(e); // java.lang.OutOfMemoryError

OutOfMemoryError (String s)

Constructs an OutOfMemoryError with the specified detail message.

final var e = new OutOfMemoryError("abcd");
System.out.println(e); // java.lang.OutOfMemoryError: abcd
System.out.println(e.getMessage()); // abcd

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page