Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 863
Solaraeus Avatar asked Feb 16 '12 17:02

Solaraeus


2 Answers

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

like image 87
Matyas Avatar answered Sep 23 '22 11:09

Matyas


You could fire off their programs using a new Process and then redirecting its error stream to check for stack overflow.

like image 37
Tudor Avatar answered Sep 23 '22 11:09

Tudor