Skip to content

Latest commit

 

History

History
25 lines (18 loc) · 1.62 KB

7e2a.md

File metadata and controls

25 lines (18 loc) · 1.62 KB

Back to questions

7e2a: Stack overflow

Disclaimer: in this question we will use Java's exception throwing mechanism to probe the size of the runtime stack. This is simply so that you can get some feeling for how the Java runtime works, and to show you more examples of how exceptions work. However, it would be very bad practice to write a real application that deliberately causes a stack overflow, even if you catch the resulting exception.

At runtime, the Java Virtual Machine reserves a certain amount of memory for the program stack. Each time a method is called, a new frame is pushed on to the stack. This allows recursive programs, where the stack may contain many frames corresponding to the same method.

If the stack size limit is reached, the JVM throws a StackOverflowError. This kind of exception is an error: the maximum stack size is a factor external to the running application (this size varies from platform to platform) and an application typically cannot recover from a stack overflow. StackOverflowError extends VirtualMachineError, an abstract class from which all errors that can be thrown by the JVM are descended.

Write a program that calls an infinitely recursive method, so that a StackOver``flowError will be thrown. Figure out a way to count how many times your method has been invoked at the point where the stack overflow error is thrown, and have this number printed to the console.

Run your program several times. What do you notice? What does this tell you about the maximum stack size of a Java program?

Hint: You will have to catch a StackOverflowError.