while (true) {
try {
if (count++ == 0) throw new Exception();
System.out.println("No exception");
} catch (Exception e) {
System.out.println("Exception thrown");
} finally {
System.out.println("in finally clause");
if (count == 2) break;
}
}
輸出證明 finally 無論有無異常都執行。
將 try 置於迴圈,配合計數器限制重試次數,實現「嘗試→失敗→清理→重試」健壯流程。
int attempts = 0;
while (attempts < MAX) {
try {
riskyOperation();
break;
} catch (TransientException e) {
attempts++;
} finally {
cleanup();
}
}
彌補 Java 異常無法「恢復至拋出點」的限制,透過迴圈重試實現語義上的恢復。