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.
9
votes
3 Answers
14
votes
When calling the methods of your students, you should embed the calls in try-catch blocks and catch Exception
s 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 Throwable
s you will catch:
- Normal
Exception
s - which enforce you to usetry-catch
orthrows
(eg.IOException
) RuntimeException
s - which bubble up through methods (eg.NullPointerException
)Error
s - eg.StackOverflowError
See the official Java Docs on the Throwable
object
2
votes