java - catch语句后返回到之前的位置

标签 java try-catch

我有一段代码在 try 语句中有一个循环。当异常被抛出并被捕获时,循环被中断,并继续执行。在 catch block 完成后,我如何才能继续执行循环的其余部分?

这是我的代码片段:

private ArrayList<URL> download(final InputStream in, URL url, int maxDepth) throws IOException {
  try {
    ...
    for (final URL link : links) {
      //if exception is caught, loop will be broken here.........
      download(link.openStream(), link, maxDepth - 1);
    }
    return alLinks;

  } catch (final IOException e) {
    // Display an error if anything fails.
    this.searchResults.append(e.getMessage());
    return null;
  }
}

我想知道是否有任何简单的方法可以在 for 循环结束之前回到正确的位置,以便它可以完成对其余元素的迭代..

非常感谢!

最佳答案

try-catch block 移到 for 循环中。

private ArrayList<URL> download(final InputStream in, URL url, int maxDepth) throws IOException {
    ...
    for (final URL link : links) {
      //if exception is caught, loop will be broken here.........
      try{
        download(link.openStream(), link, maxDepth - 1);
      }
      catch (final IOException e) {
    // Display an error if anything fails.
    this.searchResults.append(e.getMessage());
      }
    }
    return alLinks;
}

关于java - catch语句后返回到之前的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5608970/

相关文章:

java - Rails 3 中的路由错误

java - 无法解析 TabHost 方法上的符号 android

java - Java Gradle API 的 Maven 依赖参数是什么?

java - 防止系统托盘图标在单击时窃取焦点

vb.net - 是否有更好的方法让Visual Studio在 Debug模式下忽略try/catch

java - 如何解决有关不兼容类型的错误?

java - Jasper Server - MSWord 导出多个文件

java - 在 Java 中使用 Try-Catch 防止错误与忽略错误

java - 在 Java 中,如何删除 I/O 代码的构造函数中的 try catch block

c# - 尝试/最终阻止与调用处置?