Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

WithoutBook Forum

Ques. Why try-finally block prevents StackOverflowError?

- Like the below example:

public static void foo() {
try {
foo();
} finally {
foo();
}
}

public static void bar() {
bar();
}

Here bar gets stackoverflow error. But foo does not throw.

Posted on Jul 12, 2014 by Raman
Ans. It doesn't run forever. Each stack overflow causes the code to move to the finally block. The problem is that it will take a really, really long time. The order of time is O(2^N) where N is the maximum stack depth.

For maximum depth is 5:
To work each level into the finally block take twice as long an the stack depth could be 10,000 or more. If you can make 10,000,000 calls per second, this will take 10^3003 seconds or longer than the age of the universe.
Posted on Jul 12, 2014 by Arindam

Ans. Suppose there is catch block also available.

What happens here, if it comes to try block and recursively it calls same method, comes stackoverflow error and comes to catch block.
Now before catch code execution finally block code occurs and when it looks that in finally again recursive call is there then it goes to call the method again, so here it does not get any chance to print exception.
Posted on Jul 16, 2014 by Neha

Enter your Answer

Name
Email Address
Answer
©2024 WithoutBook