java 处理异常后如何恢复代码操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5210720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to resume code operation after handle exception?
提问by Wai Loon II
Q : How to resume code operation after a handled exception ? i now using try and catch.
Q:异常处理后如何恢复代码操作?我现在使用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 ?
有些网址已损坏,那么我如何跳过损坏的网址并继续使用其他网址?
回答by Mat
Depends on how you iterate over your URLs. For example:
取决于您如何遍历 URL。例如:
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.
这将处理列表中的所有 url,即使某些处理引发异常。
回答by Bozho
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);
}
}
回答by lukastymo
Try this:
试试这个:
for (url : allUrls) {
try {
Process url and render the text and save contents to text file.
} catch(Exception ex) {
...
continue;
}
}
回答by DaTroop
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
}
}
回答by Christopher
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.
像这样想。你的“进程网址”是一个循环是吗?当它发现异常时,它退出进程循环到 catch 块,然后到算法结束。
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.
您需要在进程循环中嵌套整个 try catch 块。这样,当它遇到异常时,它会返回到循环的请求而不是程序的结尾。