1

Is the stack emptied in Java when a StackOverflowError is thrown?

In other words, what happens to the stack if I write the following recursion:

public void Test()
{
    System.out.println("TEST");
    try
    {
        Test();
    }
    catch(StackOverflowError e)
    {
        Test();
    }
}
ADTC
  • 8,999
  • 5
  • 68
  • 93
vanxa
  • 11
  • 3
  • You can't use void keyword in a constructor. – Jakub H May 20 '14 at 11:48
  • 1
    @Jakub It's a syntactically valid method signature (not a constructor). The OP merely ignored the naming convention that method names should start with a lowercase letter. – ADTC May 20 '14 at 11:53
  • 1
    @ADTC Yeah, I realised that after I wrote it. That's why naming conventions are important :) – Jakub H May 20 '14 at 11:59
  • In my experience the app will come down hard. (The JVM reserves some stack for handling StackOverflow, but once that reserved stack is used up there is nothing the JVM can do other than commit Hoot Gibson. – Hot Licks May 21 '14 at 15:36

2 Answers2

1

Test() method in catch block throws another StackOverflowError.

keles
  • 136
  • 4
1

This raises a lot of StockOverflowErrors! Assuming the maximumstack depth your configuration supports is 1000 calls, then this throw 2^1000 exceptions! Each call to Test() calls the Test() functions once in the try clause and once in the catch clause, so it is an exponential number of Errors that are thrown (and catched), until the final one is delegated to the top.

But to answer your question in the titel: The stack is discarded, up to the function that catches your exception.

Daniel
  • 27,718
  • 20
  • 89
  • 133
  • 1
    Wrong! It's not 1000^2, but rather 2^1000. Hence this code is really just a glorified while(true) with flow control via exception capture, since even with a 128-element stack this would be executed for years – Ordous May 20 '14 at 12:05
  • @Ordous: Correct! I update the answer to reflect your finding :). – Daniel May 21 '14 at 15:28