我必須做一個函數調用。如果失敗,我再試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