自编程Java以来,我需要多次编程这样的事情:
做一些可能失败的事情.如果失败,请再试一次,但最多3次(或2次或5次).
这种方法应该有效:
for (int i = 0; i < 3; i++) {
try {
doSomething();
} catch(BadException e) {
continue;
}
break;
}
Run Code Online (Sandbox Code Playgroud)
但我不认为这是非常富有表现力的.你有更好的解决方案吗?
像这样的东西会很好:
try (maxTimes = 3) {
doSomething();
} catch(BadException e) {
retry;
}
Run Code Online (Sandbox Code Playgroud)
要么:
try (maxTimes = 3) {
doSomething();
if(somethingFailed()) {
retry;
}
}
Run Code Online (Sandbox Code Playgroud)
但这对Java来说是不可能的.你知道一种可能的语言吗?
Java不会让您发明自己的语法,但您可以定义自己的方法来帮助您用更少的代码表达概念:
public static boolean retry(int maxTries, Runnable r) {
int tries = 0;
while (tries != maxTries) {
try {
r.run();
return true;
} catch (Exception e) {
tries++;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
现在你可以像这样调用这个方法:
boolean success = retry(5, () -> doSomething());
// Check success to see if the action succeeded
// If you do not care if the action is successful or not,
// ignore the returned value:
retry(5, () -> doSomethingElse());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |