java中途强制跳出递归

有些时候我们需要在中途强制跳出递归,而且还是需要一步跳出,而不一层一层的跳出,这时,我们可以采用抛异常的方法来实现。

 class Test {
	 static class StopMsgException extends RuntimeException {
	  }
    public static void main(String args[]) {
        try {
        	run(0);
        } catch (StopMsgException e) {
            System.out.println(e);
        }
    }
 
    public static void run(int t) {
 
        if (t > 20) {
            // 跳出
            throw new StopMsgException();
        }
        // 执行操作
        System.out.println(t);
        // 递归
        run(t + 1);
    }
 
   
}

这个小例子就是实现该功能的方法

原文地址:https://www.cnblogs.com/oversea201405/p/3752138.html