Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

According to the Java Language Specification, §11.1.1, "The Kinds of Exceptions" [JLS 2013],

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes.

...

Catching Throwable is disallowed in general by ERR08-J. Do not catch NullPointerException or any of its ancestors, but it is permitted when filtering exception traces by the exception ERR08-EX0 in that rule.

Noncompliant Code Example

This noncompliant code example generates a StackOverflowError as a result of infinite recursion. It exhausts the available stack space and may result in denial of service.

Code Block
bgColor#FFcccc
public class StackOverflow {
  public static void main(String[] args) {
    infiniteRun();
    // ...
  }
    
  private static void infiniteRun() {
    infiniteRun();
  }
}

Compliant Solution

This compliant solution shows a try-catch block that can be used to capture java.lang.Error or java.lang.Throwable. A log entry can be made at this point, followed by attempts to free key system resources in the finally block.

...

Note that this solution catches Throwable in an attempt to handle the error; it falls under exception ERR08-EX2 in ERR08-J. Do not catch NullPointerException or any of its ancestors.

Applicability

Allowing a system error to abruptly terminate a Java program may result in a denial-of-service vulnerability.

In the event of actually running out of memory, it is likely that some program data will be in an inconsistent state. Consequently, it might be best to restart the process. If an attempt is made to carry on, reducing the number of threads may be an effective workaround. This measure can help in such scenarios because threads often leak memory, and their continued existence can increase the memory footprint of the program.

The methods Thread.setUncaughtExceptionHandler() and ThreadGroup.uncaughtException() can be used to help deal with an OutOfMemoryError in threads.

Bibliography

[JLS 2013]§11.2, "Compile-Time Checking of Exceptions"
[Kalinovsky 2004]Chapter 16, "Intercepting Control Flow: Intercepting System Errors"

...