Search code examples
javamultithreadingstack-overflow

How do I catch and recover from a stack overflow in Java?


I am writing a grading program for an assignment in which students are implementing recursive sort algorithms. This means several students will probably turn in broken code which causes stack overflow. I would like to somehow catch stack overflows that occur when calling the students code so I can deduct from their score and continue on to other tests. Unfortunately, stack overflow doesn't seem to go through the standard path of other exceptions - try/catch blocks don't seem to help. Is there a way to return execution to my code after a stack overflow has occurred? I've looked into using threads to do this, but it just seems to come back to not being able to use try/catch.


Solution

  • When calling the methods of your students, you should embed the calls in try-catch blocks and catch Exceptions as Throwables.

    See the following code:

    public class Test {
        /**
         * @param args
         */
        public static void main(String[] args) {
            try {
                soe();
            } catch (Throwable e) {
                System.out.println("Caught:" + e
                        + ", everything went better than expected.");
            }
        }
        /**
         * Method producing StackOverflowError
         */
        public static void soe() {
            soe();
        }
    }
    

    More info

    When catching Throwables you will catch:

    • Normal Exceptions - which enforce you to use try-catch or throws (eg. IOException)
    • RuntimeExceptions - which bubble up through methods (eg. NullPointerException)
    • Errors - eg. StackOverflowError

    See the official Java Docs on the Throwable object