[英]how to resume code operation after handle exception?
问:处理异常后如何恢复代码操作? 我现在使用try and catch。
Try
{
Process url and render the text and save contents to text file.
}Catch(Exception ex)
}
有些网址已损坏,那么如何跳过损坏的网址并继续使用其他网址?
取决于您如何遍历URL。 例如:
for (URL url: urllist) {
try {
// Process **one** url
} catch (Exception ex) {
// handle the exception
}
}
即使某些处理引发异常,这也会处理列表中的所有url。
就是这样-不执行任何操作(除了可能记录警告),然后代码执行将继续。 例如:
for (String url : urls) {
try {
// parse, open, save, etc.
} catch (Exception ex) {
log.warn("Problem loading URL " + url, ex);
}
}
尝试这个:
for (url : allUrls) {
try {
Process url and render the text and save contents to text file.
} catch(Exception ex) {
...
continue;
}
}
创建两个这样的方法:
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
}
}
此伪代码中存在逻辑错误。
这样想吧。 您的“过程网址”是一个循环,是吗? 当发现异常时,它退出流程循环,到达catch块,然后到达算法结尾。
您需要将整个try catch块嵌套在流程循环中。 这样,当它遇到异常时,它将返回到循环的开头,而不是返回到程序结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.