Breaking out of a recursion in java

后端 未结 11 1468
故里飘歌
故里飘歌 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条回答
  •  猫巷女王i
    2020-12-01 05:23

    I'd recommend an exception handling. That makes clear, that the recursion was aborted because of some violation (or other exception):

    public void outer() {
      try {
        int i = recurse(0);
      } catch (OuchException ouch) {
        // handle the exception here
      }
    }
    
    private int recurse(int i) throws OuchException {
    
        // for tree-like structures
        if (thisIsALeaf) {
           return i;
        }
    
        // the violation test
        if (itHurts)
           throw new OuchException("That really hurts");
    
        // we also can encapsulate other exceptions
        try {
           someMethod();
        } catch (Exception oops) {
           throw new OuchException(oops);
        }
    
        // recurse
        return recurse(i++);
    }

    Sure, it violates the initial requirement to return 'true' upon abortion. But I prefer a clean separation of return values and notification on abnormal behaviour.

提交回复
热议问题