当前位置: 首页 > 新闻动态 > 软件编程

Java 跳出递归循环问题解决办法

作者:用户投稿 浏览: 发布日期:2026-01-11
[导读]:这篇文章主要介绍了 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);
  }
}

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

免责声明:转载请注明出处:http://sczxchw.cn/news/163778.html

扫一扫高效沟通

多一份参考总有益处

免费领取网站策划SEO优化策划方案

请填写下方表单,我们会尽快与您联系
感谢您的咨询,我们会尽快给您回复!