Error and the errors a program cannot catch

Throwable has two branches, and everything in this part so far was Exception. The other one is Error: a failure of the JVM or of the machine rather than of the program's logic, such as no stack left and no heap left. A program may catch an Error, and it usually should not, and the two cases below show why the distinction is worth keeping.

StackOverflowError

Every call takes a frame from a fixed stack. A recursion without a base case fills the stack, and the JVM stops it with an Error instead of letting the machine run out of memory:

public class Deep { static int depth; public static void main(String[] args) { try { count(0); } catch (StackOverflowError e) { System.out.println("caught: " + e.getClass().getSimpleName()); System.out.println("depth above 10000: " + (depth > 10_000)); System.out.println("frames in the trace: " + e.getStackTrace().length); } } static void count(int n) { depth = n; count(n + 1); } }

javac -Xlint:all Deep.java
java Deep

caught: StackOverflowError
depth above 10000: true
frames in the trace: 1024

The depth is around twenty thousand calls on this container, and the exact number depends on the stack size and on how many frames the method needs, so the program prints whether it is above ten thousand rather than the number. The trace holds 1024 frames because that is the JVM default, -XX:MaxJavaStackTraceDepth, so a longer trace is cut.

Catching the error here is a demonstration and not a design: a method that has overflowed its stack has no reliable state left. The real lesson of lesson 019 stands, which is that a recursion needs a base case, and a deep one is better written as a loop.

OutOfMemoryError

The heap is the other fixed resource. An array is allocated as one block, so an array larger than the JVM can address fails before any of its elements is used, and the message says which limit was hit:

public class Huge { public static void main(String[] args) { try { long[] numbers = new long[Integer.MAX_VALUE]; System.out.println("allocated " + numbers.length); } catch (OutOfMemoryError e) { System.out.println("caught: " + e.getClass().getSimpleName()); System.out.println("message: " + e.getMessage()); } } }

javac -Xlint:all Huge.java
java Huge

caught: OutOfMemoryError
message: Requested array size exceeds VM limit

The message is not Java heap space, because the request never reached the heap: an array of two billion longs is beyond the largest block the JVM will allocate. The two messages are worth telling apart, and the next program produces the other one.

A heap the program outgrows

The heap size is a flag, -Xmx, and a small one is how a program is tested against the memory it will have in production. This one allocates sixty-four megabytes:

public class Limit { public static void main(String[] args) { byte[] block = new byte[64 * 1024 * 1024]; System.out.println("allocated " + block.length + " bytes"); } }

javac -Xlint:all Limit.java
java Limit

allocated 67108864 bytes

With a heap smaller than the block, the same program ends with the other message and a trace that names the allocation line:

java -Xmx16m Limit
echo "status: $?"

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Limit.main(Limit.java:3)
status: 1

The frame is the line of the new, which is where the allocation that did not fit happened. The default heap on this container is around three gigabytes, which is why the unflagged run succeeded; the flag is the way to reproduce a small machine on a large one.

What a program can do

An Exception says that a piece of work failed and the program can choose another path. An Error says that the environment of the program failed: no stack, no heap, a class that cannot be loaded, a link that is broken. The convention is not to catch one, because the state after it is not trustworthy and the memory needed to report it may be the memory that is missing.

What a program can do about memory is a design rather than a catch: holds less at once, streams a file instead of reading it whole (lesson 105), sets a bound on a cache, and measures with -Xmx before the production machine measures it. What it can do about the stack is to write the recursion as a loop or to bound its depth. The concurrency part adds one more answer, the virtual thread of lesson 122, whose stack is not the fixed one of a platform thread.

Exercises

  1. Add a base case to count and check that no error is thrown.
  2. Run Huge with -Xmx32m and read which of the two messages appears.
  3. Change Limit to allocate in a loop of one-megabyte blocks and run it with -Xmx16m.
  4. Catch the OutOfMemoryError of the loop and print how many blocks were allocated before it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which branch of Throwable is an Error?

    Answer

    The one for a failure of the JVM or the machine, not of the logic

    No stack, no heap and a broken class are environmental, and the program usually cannot continue.

  2. What does a StackOverflowError mean?

    Answer

    The calls used the whole stack, usually through a recursion without a base case

    Each call takes a frame from a fixed stack, and a recursion without an end fills it.

  3. What does -Xmx16m do?

    Answer

    Sets the maximum heap to sixteen megabytes

    The flag is the maximum heap, which is how a small machine is reproduced.

  4. What does this program print? public class Q1 { static int depth; static void down() { depth++; down(); } public static void main(String[] args) { try { down(); } catch (StackOverflowError e) { System.out.println(e.getClass().getSimpleName()); System.out.println(depth > 100); } } }

    Answer

    StackOverflowError / true

    The recursion fills the stack after far more than a hundred calls.

  5. Why is catching an OutOfMemoryError usually a bad idea?

    Answer

    The program has no reliable state left and may need memory to report it

    The environment failed, and the code that follows may fail again at any allocation.

  6. What does the message "Requested array size exceeds VM limit" mean?

    Answer

    The array itself is too large for the JVM to allocate, before the heap is asked

    The request is beyond the largest single block, which is a different failure from Java heap space.

  7. Why does the depth of a stack overflow differ between machines?

    Answer

    It depends on the stack size and on the frames each call needs

    The stack is a fixed size per thread, and a frame is a few dozen bytes of it.

  8. What does this program print? public class Q2 { public static void main(String[] args) { try { long[] a = new long[Integer.MAX_VALUE]; System.out.println("allocated"); } catch (OutOfMemoryError e) { System.out.println(e.getMessage()); } } }

    Answer

    Requested array size exceeds VM limit

    The array is too large to allocate as one block, which is the message of the Huge program.

  9. What does this program print? public class Q3 { public static void main(String[] args) { try { throw new OutOfMemoryError("full"); } catch (OutOfMemoryError e) { System.out.println("caught " + e.getMessage()); } } }

    Answer

    caught full

    An Error may be caught like any Throwable, which is why the lesson says it usually should not be.

  10. What is the practical answer to a memory problem in a program?

    Answer

    Hold less at once and measure with -Xmx

    The heap is a design constraint, and the measurement on a small heap shows whether the design fits.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev