Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Why can StackOverflowError be handled? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why can StackOverflowError be handled?" Watch "Why can StackOverflowError be handled?" New topic
Author

Why can StackOverflowError be handled?

Leon Omk
Ranch Hand

Joined: Aug 17, 2010
Posts: 75



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?

OK, so that other guy knows Java better than I do, but I bet he can't speak Wuhanese(a Chinese Dialect) like me.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3598
    
  14

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

Joined: Aug 22, 2010
Posts: 3606
    
  60

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.
 
 
subject: Why can StackOverflowError be handled?
 
Similar Threads
Calling Main method Recursively.
Will reference to the same type create a memory leak?
why object defined in the method are created in the heap memory?
Question about mem allocation for recursive functions
java.lang.StackOverflowError