Search code examples
javaexceptionjakarta-eestack-overflow

How can I handle StackOverflowError in Java?


How can I handle StackOverflowError in Java?


Solution

  • 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.