简体   繁体   中英

Handle stack overflow exception in a endless recursive call

I have a situation like below

class a{
    public void process(){
      System.out.println("ABC");
      process();
    }
}

while I'm executing at certain point I'm getting stack overflow exception. On my situation I can't change the recursive call logic. So for a work around I try to catch the error and made a gc call again initiate the process() method. Whether is it a good solution... or what is the better solution to keep the recursive call alive infinitely.

Your recursive call uses up a stack frame in the JVM each time recursion occurs, making a stack overflow error inevitable.

The best solution in Java is to use iteration instead. For example:

public void process() {
    while (true) {
        processOnce();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM