Java:我将如何编写 try-catch-repeat 块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1731504/
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
Java: How would I write a try-catch-repeat block?
提问by Legend
I am aware of a counter approach to do this. I was wondering if there is a nice and compact way to do this.
我知道有一种反方法可以做到这一点。我想知道是否有一种很好且紧凑的方法来做到这一点。
回答by oxbow_lakes
Legend - your answer could be improved upon; because if you fail numTriestimes, you swallow the exception. Much better:
传说 - 您的答案可以改进;因为如果你失败了numTries几次,你就会吞下异常。好多了:
while (true) {
try {
//
break;
} catch (Exception e ) {
if (--numTries == 0) throw e;
}
}
回答by Legend
I have seen a few approaches but I use the following:
我已经看到了一些方法,但我使用以下方法:
int numtries = 3;
while(numtries-- != 0)
try {
...
break;
} catch(Exception e) {
continue;
}
}
This might not be the best approach though. If you have any other suggestions, please put them here.
但这可能不是最好的方法。如果您有任何其他建议,请将它们放在这里。
EDIT: A better approach was suggested by oxbow_lakes. Please take a look at that...
编辑:oxbow_lakes 提出了更好的方法。请看看那个...
回答by abalogh
if you are using Spring already, you might want to create an aspect for this behavior as it is a cross-cutting concern and all you need to create is a pointcut that matches all your methods that need the functionality. see http://static.springsource.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj-example
如果您已经在使用 Spring,您可能希望为此行为创建一个方面,因为它是一个横切关注点,您需要创建的只是一个切入点,该切入点与您需要该功能的所有方法相匹配。见http://static.springsource.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj-example
回答by yegor256
Try aspect oriented programming and @RetryOnFailureannotation from jcabi-aspects:
@RetryOnFailure从jcabi-aspects尝试面向方面的编程和注释:
@RetryOnFailure(attempts = 2, delay = 10, verbose = false)
public String load(URL url) {
return url.openConnection().getContent();
}

