我有一段代码在 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/