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/bhlsheji/p/4637559.html