how to resume code operation after handle exception?
Q : How to resume code operation after a handled exception ? 开发者_运维问答 i now using try and catch.
Try
{
Process url and render the text and save contents to text file.
}Catch(Exception ex)
}
Some urls are broken, so how do i skip broken urls and continue with other urls ?
Depends on how you iterate over your URLs. For example:
for (URL url: urllist) {
try {
// Process **one** url
} catch (Exception ex) {
// handle the exception
}
}
This will process all urls in the list, even if some of the processing raises an exception.
That's it - do nothing (apart from perhaps logging a warning), and the code execution will continue. Ex:
for (String url : urls) {
try {
// parse, open, save, etc.
} catch (Exception ex) {
log.warn("Problem loading URL " + url, ex);
}
}
Try this:
for (url : allUrls) {
try {
Process url and render the text and save contents to text file.
} catch(Exception ex) {
...
continue;
}
}
There is a logical error in this pseudo-code.
Think about it like this. Your 'process url' was a loop yes? When it found an exception it exited the process loop to the catch block and then to the end of the algorithm.
You need to nest the entire try catch block in the process loop. That way when it hits an exception it returns to the begging of the loop and not to the end of the program.
Create two methods like this:
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
}
}
精彩评论