处理异常后如何恢复代码操作?

时间:2011-03-06 13:19:34

标签: java

问:如何在处理异常后恢复代码操作?     我现在使用try和catch。

Try
{
    Process url and render the text and save contents to text file.
}Catch(Exception ex)
}

有些网址坏了,所以我如何跳过破坏的网址并继续使用其他网址?

5 个答案:

答案 0 :(得分:8)

取决于您如何迭代您的网址。例如:

for (URL url: urllist) {
  try {
    // Process **one** url
  } catch (Exception ex) {
    // handle the exception
  }
}

这将处理列表中的所有网址,即使某些处理会引发异常。

答案 1 :(得分:4)

就是这样 - 什么都不做(除了可能记录警告),代码执行将继续。例如:

for (String url : urls) {
    try {
        // parse, open, save, etc.
    } catch (Exception ex) {
        log.warn("Problem loading URL " + url, ex);
    }
}

答案 2 :(得分:2)

试试这个:

for (url : allUrls) {
   try {
       Process url and render the text and save contents to text file.
   } catch(Exception ex) {
      ...
      continue;
   }
}

答案 3 :(得分:0)

创建两个这样的方法:

public void processAllURLs(final List<String> urls){
    for(String url: urls){
        processURL(url);
    }
}

public void processURL(final String url){
    try {
        // Attempt to process the URL
    } catch (Exception ex) {
        // Log or ignore
    }
}

答案 4 :(得分:0)

此伪代码存在逻辑错误。

这样想。你的'进程网址'是一个循环是吗?当它发现异常时,它退出进程循环到catch块,然后到算法结束。

您需要在流程循环中嵌套整个try catch块。这样当它遇到异常时它返回到循环的乞讨而不是程序的结束。

相关问题