Catching OutOfMemoryError

ID

java.catch_outofmemoryerror

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:755, reliability

Description

Reports catch (OutOfMemoryError …​) blocks. Catching OutOfMemoryError is almost always incorrect because the JVM may be in an inconsistent state after running out of memory.

Rationale

When an OutOfMemoryError is thrown, there is no guarantee that the catch handler can execute safely — it may itself require memory allocation. Finalizers and weak references may not have run, data structures may be half-initialized, and thread pools may be starved. Catching OOM gives a false sense of recovery.

// Bad - OOM leaves the JVM in an unreliable state
try {
    byte[] data = new byte[hugeSize];
} catch (OutOfMemoryError e) {
    // JVM may not be able to execute this reliably
    data = new byte[0];
}

Remediation

Do not catch OutOfMemoryError. Instead, validate input sizes before allocation, configure the JVM heap appropriately, or let the error propagate so the process can be restarted cleanly.

// Good - validate size upfront
if (size > MAX_ALLOWED_SIZE) {
    throw new IllegalArgumentException("Size too large: " + size);
}
byte[] data = new byte[size];