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.
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:
Exception
s - which enforce you to use try-catch
or throws
(eg. IOException
)RuntimeException
s - which bubble up through methods (eg. NullPointerException
)Error
s - eg. StackOverflowError
See the official Java Docs on the Throwable
object
You could fire off their programs using a new Process
and then redirecting its error stream to check for stack overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With