Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle StackOverflowError in Java? [closed]

How can I handle StackOverflowError in Java?

like image 667
Silent Warrior Avatar asked Jun 04 '09 16:06

Silent Warrior


People also ask

Can we catch StackOverflowError in Java?

StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.

Can we handle stack overflow error?

Stack overflow means, that you have no room to store local variables and return adresses. If your jvm does some form of compiling, you have the stackoverflow in the jvm as well and that means, you can't handle it or catch it.

How do I stop stack overflow error?

One method to prevent stack overflow is to track the stack pointer with test and measurement methods. Use timer interrupts that periodically check the location of the stack pointer, record the largest value, and watch that it does not grow beyond that value.


1 Answers

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.

like image 68
Huxi Avatar answered Oct 11 '22 02:10

Huxi