在Java项目中如何跳出递归循环

今天就跟大家聊聊有关在Java项目中如何跳出递归循环,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

 使用异常跳出循环

1、如果方法体内含有需要抛出异常的对象,让方法直接抛出异常,不要在方法体内捕获

public void xxxx() throws Exception

2、如果方法体内不含有需要抛出异常的对象

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

看完上述内容,你们对在Java项目中如何跳出递归循环有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。