首页 > 解决方案 > 重复某件事直到成功,但最多 3 次

问题描述

自从编写 Java 以来,我需要多次编写这样的程序:

做一些可能失败的事情。如果失败,请再试一次,但最多 3(或 2 或 5)次。

这种方法应该有效:

for (int i = 0; i < 3; i++) {
    try {
        doSomething();
    } catch(BadException e) {
        continue;
    }
    break;
}

但我不认为它很有表现力。你有更好的解决方案吗?

像这样的东西会很好:

try (maxTimes = 3) {
    doSomething();
} catch(BadException e) {
    retry;
}

或者:

try (maxTimes = 3) {
    doSomething();
    if(somethingFailed()) {
        retry;
    }
}

但这对于 Java 是不可能的。你知道一种语言可以使用它吗?

标签: 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;
}

现在你可以像这样调用这个方法:

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());

演示。


推荐阅读