Do Not Catch java.lang.Error

ID

java.no_catch_error

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:396, reliability

Description

Reports catch blocks that catch Error or java.lang.Error.

Rationale

Error and its subclasses (OutOfMemoryError, StackOverflowError, VirtualMachineError, etc.) indicate serious JVM-level conditions that application code cannot reliably recover from. Catching them hides the condition and may leave the JVM in a corrupt or unpredictable state.

// Bad — application cannot recover from OOM
try {
    allocateLargeBuffer();
} catch (Error e) {
    log.warn("allocation failed");
}

Remediation

Let Error propagate so that the JVM or container runtime can handle it (restart, alert, heap dump). If specific error handling is truly needed, catch the narrowest Error subclass and document the justification:

// Good — let errors propagate
try {
    allocateLargeBuffer();
} catch (IllegalArgumentException e) {
    log.warn("bad size", e);
}