2011-03-06 89 views
1

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

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

有些网址已损坏,那么如何跳过损坏的网址并继续与其他网址?

回答

8

取决于您如何遍历URL。例如:

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

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

4

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

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

试试这个:

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

2017年,'错误:继续在循环外? – YumYumYum 2017-06-28 08:32:40

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 
    } 
} 
0

有在这个伪代码的逻辑错误。

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

您需要将整个try catch块嵌套在进程循环中。这样,当它遇到一个异常时,它会返回到循环的开始处,而不是程序结束。