Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java OutOfMemoryError not caught by clauses that catch Error and Throwable

When I run the code below, an OutOfMemoryError is thrown, but is not caught, despite the fact that there are clauses that should catch it:

public class SomeClass {
    public static void main(String[] args) {
        try {
            //Allocate a huge amount of memory here
        } catch (OutOfMemoryError oome) {
            System.out.println("OutOfMemoryError=<" + oome + ">");
        } catch (Error err) {
            System.out.println("Error=<" + err + ">");
        } catch (Throwable t) {
            System.out.println("Throwable=<" + t + ">");
        } finally {
            System.out.println("'Finally' clause triggered");
        }
    }
}

The output is as follows:

'Finally' clause triggered
Exception in thread "main"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"

The fact that the exception is not caught makes no sense to me. The OutOfMemoryError documentation confirms that the exception should be caught by either Throwable, Error, or OutOfMemoryError. (Note that the "java.lang." specifier does not affect the behavior.)

All the other questions that I've seen here on StackOverflow along the lines of "Why isn't my OutOfMemoryError exception being caught?" were posted by people who were only catching Exception objects, not Error or Throwable.

Any idea as to what's going on?

like image 264
Alan Avatar asked Nov 27 '22 21:11

Alan


1 Answers

Inside of your exception handler you're trying to allocate the string "OutOfMemoryError=<" + oome + ">", but you're out of memory and so this is probably going to throw another OutOfMemoryError

like image 186
Zim-Zam O'Pootertoot Avatar answered Dec 15 '22 02:12

Zim-Zam O'Pootertoot