我必须做一个函数调用。如果失败,我再试2次。如果它在2次重试后仍然失败,我会抛出异常。如何使用try catch重试机制为for循环编写更短,更高效的代码?
下面是它的工作我当前的代码:
for (int retry = 0; retry < 4; retry++) {
try {
callFunction();
break;
} catch (Exception e) {
if (retry >= 0 && retry < 3) {
warn("callFunction failed. Retrying.." +(retry+1));
} else {
warn("Retried maximum number of "+(retry+1)+" times. Failing the script");
e.printStackTrace();
}
}
}
OUTPUT:
callFunction failed. Retrying..1
callFunction failed. Retrying..2
callFunction failed. Retrying..3
Retried maximum number of 4 times. Failing the script
我明白,这是不是即使它正在编写的最有效方式。你能帮我重构一下这段代码,以符合Java干净代码的最佳实践标准吗?
我投票结束这个问题作为题外话,因为它属于[codereview.se]。 – shmosel
另请阅读[tag:coding-style]标签的说明。 – shmosel