How to handle StackOverflowError in Java?

Silent Warrior picture Silent Warrior · Jun 4, 2009 · Viewed 85.3k times · Source

How to handle StackOverflowError in Java ?

Answer

Huxi picture Huxi · Jun 4, 2009

I'm not sure what you mean with "handle".

You can certainly catch that error:

public class Example {
    public static void endless() {
        endless();
    }

    public static void main(String args[]) {
        try {
            endless();
        } catch(StackOverflowError t) {
            // more general: catch(Error t)
            // anything: catch(Throwable t)
            System.out.println("Caught "+t);
            t.printStackTrace();
        }
        System.out.println("After the error...");
    }
}

but that is most likely a bad idea, unless you know exactly what you are doing.