Breaking out of a recursion in java

后端 未结 11 1467
故里飘歌
故里飘歌 2020-12-01 04:23

The recursion is sort of a \'divide and conquer\' style, it splits up while getting smaller (Tree data structure), and I want it to break completely if a violation is found,

11条回答
  •  误落风尘
    2020-12-01 05:16

    The best way to get out of a recursive loop when an error is encountered is to throw a runtime exception.

    throw new RuntimeException("Help!  Somebody debug me!  I'm crashing!");
    

    Of course, this kills your program, but you should employ range checking and algorithm analysis to make sure your recursion does not throw such an exception. One reason you might want to break out of a recursive algorithm is that you are running low on memory. Here, it is possible to determine how much memory your algorithm will use on the stack. If you are coding Java, say, compare that calculation to

    getMemoryInfo.availMem().
    

    Let's say you are using recursion to find n!. Your function looks something like this:

    public long fact(int n)
    {
        long val = 1;
        for (int i  = 1, i<=n,i++)
            return val *= fact(i);
        return val;
    }
    

    Before you run it, check that you have (number of bytes in a long, 8 in Java) * n bytes in memory to hold the whole stack. Basically, with range and error checking in advance of the recursive method/function, you shouldn't need to break out. Depending on your algorithm, however, you may need to signal to the whole stack that you're good to go. If that's the case, Tom's answer works.

提交回复
热议问题