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

 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);
    }
 
   
}

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

相关文章:

  • 2022-01-22
  • 2021-11-29
  • 2021-07-31
  • 2021-10-29
  • 2021-04-18
  • 2021-08-30
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-10
  • 2021-11-24
  • 2021-06-23
  • 2021-04-04
相关资源
相似解决方案