• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why can StackOverflowError be handled?

 
Leon Omk
Ranch Hand
Posts: 75
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I'm wondering when the stack is already overflown, why JVM still has resources(memory, extra space in stack) to handle this error? Any idea?
 
Stephan van Hulst
Bartender
Pie
Posts: 5889
63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens when the exception is thrown? It propagates up the stack, effectively popping stack frames, until it reaches the main method again where it is caught. You should have just as much space on the stack before you call go(), as after you call it.
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When any exception happens, the virtual machine searches the stack for active exception handlers (compatible catch blocks), unwinding the stack in the process. When your exception handler in the main() method is found, the stack is already nearly empty (only the main method is on the stack, apart perhaps from some of the VM bootstrap methods); all the go() calls were already removed.

Try modifying your test to handle the exception in the go() method itself - that way the exception handler will be found and executed when the stack is still full. If you call another method from the exception handler, chances are you'll get another StackOverflowException. You'll have to craft the test very carefully to get a good image of what is going on, as an exception in the catch block will mask the original exception that caused the catch block to be executed. Therefore calling System.out methods to log things up will probably cause the stack to overflow again, preventing you from displaying all the exceptions that have occurred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic