Retry and recover from file errors
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Some failures fix themselves if you wait a moment; others never will. Good recovery code retries the first kind a limited number of times, falls back to safe defaults where that is harmless, and reports everything else clearly.
Temporary versus permanent errors
A temporary error may go away if you try again a moment later, such as a file another program has open. A permanent error gives the same result every time, such as a missing file.
Example 1 · Sorting exceptions into temporary and permanent
import java.net.SocketTimeoutException;import java.nio.charset.MalformedInputException;import java.nio.file.AccessDeniedException;import java.nio.file.FileSystemException;import java.nio.file.NoSuchFileException;import java.util.List;
public class ClassifyDemo { static boolean isTemporary(Exception e) { if (e instanceof AccessDeniedException) { return true; // often a lock on Windows; retry a few times only } if (e instanceof FileSystemException f) { String reason = f.getReason(); // Windows message text: a best-effort check return reason != null && reason.contains("being used by another process"); } return e instanceof SocketTimeoutException; }
public static void main(String[] args) { List<Exception> errors = List.of( new NoSuchFileException("marks.csv"), new AccessDeniedException("report.xlsx"), new FileSystemException("fees.csv", null, "The process cannot access the file because it is being used by another process"), new SocketTimeoutException("Read timed out"), new MalformedInputException(1), new NumberFormatException("For input string: \"x\""));
for (Exception e : errors) { String decision = isTemporary(e) ? "temporary: retry a few times" : "permanent: do not retry"; System.out.println(e.getClass().getSimpleName() + " -> " + decision); } }}NoSuchFileException -> permanent: do not retry AccessDeniedException -> temporary: retry a few times FileSystemException -> temporary: retry a few times SocketTimeoutException -> temporary: retry a few times MalformedInputException -> permanent: do not retry NumberFormatException -> permanent: do not retry
What this code does
NoSuchFileExceptionis also aFileSystemException, but its reason isnull, so it is treated as permanent. TheAccessDeniedExceptioncheck comes first because it is a subclass too.- A missing file, a wrong encoding (
MalformedInputException) and bad data give the same result on every try, so retrying them is pointless.
Other temporary errors are a busy network drive or a server that timed out; other permanent ones are a line that is not a number, a file in the wrong encoding or no permission. Retrying only makes sense for temporary errors: retrying a missing file five times just makes the user wait five times longer for the same message.
Java does not label exceptions as temporary, so you decide by type: NoSuchFileException, MalformedInputException and NumberFormatException are permanent; a SocketTimeoutException or a file in use by another program is usually temporary.
A retry loop with a limit and a wait
A retry runs the same operation again after it failed, with a limit on the number of attempts and a wait between them, so a temporary problem can clear.
A retry runs the same operation again after it failed. A safe retry loop has a limit (for example 3 attempts), a wait between attempts and a give-up step that throws the last exception when the limit is reached.
Example 2 · A retry loop with a limit and backoff
import java.io.IOException;import java.io.InterruptedIOException;
interface IoAction<T> { T run() throws IOException;}
public class RetryDemo { static <T> T retry(int maxAttempts, long firstWaitMs, IoAction<T> action) throws IOException { long wait = firstWaitMs; for (int attempt = 1; ; attempt++) { try { return action.run(); } catch (IOException e) { if (attempt == maxAttempts) { throw e; } System.out.println("Attempt " + attempt + " failed (" + e.getMessage() + "), waiting " + wait + " ms"); sleep(wait); wait *= 2; // backoff: wait longer each time } } }
static void sleep(long ms) throws InterruptedIOException { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // keep the "please stop" flag throw new InterruptedIOException("retry interrupted"); } }
static int calls = 0;
static String readMarks() throws IOException { // busy twice, then works calls++; if (calls <= 2) { throw new IOException("file busy"); } return "101,78"; }
static String readAlwaysBusy() throws IOException { throw new IOException("file busy"); }
public static void main(String[] args) { try { System.out.println("Read: " + retry(3, 100, RetryDemo::readMarks)); retry(3, 50, RetryDemo::readAlwaysBusy); } catch (IOException e) { System.out.println("Gave up: " + e.getMessage()); } }}Attempt 1 failed (file busy), waiting 100 ms Attempt 2 failed (file busy), waiting 200 ms Read: 101,78 Attempt 1 failed (file busy), waiting 50 ms Attempt 2 failed (file busy), waiting 100 ms Gave up: file busy
What this code does
retrytries the action up tomaxAttemptstimes. Each failure waits, and the wait doubles: 100 ms, then 200 ms. On the last failed attempt it stops waiting and throws, so the caller still learns what went wrong.IoActionis a small functional interface whose method may throwIOException, so method references likeRetryDemo::readMarksfit. An interrupt duringsleepends the retries with anInterruptedIOException.
The wait gives the other program time to finish. Doubling it each time (100 ms, 200 ms, 400 ms) is called backoff: it gives a slow problem more time without making a quick one wait long.
Thread.sleep can throw InterruptedException when someone asks the program to stop; then stop retrying and restore the flag with Thread.currentThread().interrupt().
Trace the code
Trace a retry loop
Variables
- maxTries
- 3
- calls
- 0
Output
(nothing printed yet)Line 13At most three attempts. calls counts how often readReport has run.
Fallback values such as default settings
A fallback is a safe value used when the real one cannot be loaded. A missing settings.properties on the first run is normal: use the default theme and font size and carry on.
Example 3 · Default settings as a fallback
import java.io.IOException;import java.io.Reader;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;import java.util.Properties;
record Settings(String theme, int fontSize) { }
public class FallbackDemo { static final Settings DEFAULTS = new Settings("light", 14);
static Settings load(Path file) { Properties p = new Properties(); try (Reader in = Files.newBufferedReader(file)) { p.load(in); } catch (NoSuchFileException e) { System.out.println("No " + file.getFileName() + " yet, using defaults"); return DEFAULTS; } catch (IOException e) { System.out.println("Could not read " + file.getFileName() + " (" + e.getClass().getSimpleName() + "), using defaults"); return DEFAULTS; }
String theme = p.getProperty("theme", DEFAULTS.theme()); String sizeText = p.getProperty("fontSize", String.valueOf(DEFAULTS.fontSize())); int fontSize; try { fontSize = Integer.parseInt(sizeText.trim()); } catch (NumberFormatException e) { System.out.println("Bad fontSize '" + sizeText + "', using " + DEFAULTS.fontSize()); fontSize = DEFAULTS.fontSize(); } return new Settings(theme, fontSize); }
public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("app"); Path file = folder.resolve("settings.properties");
System.out.println(load(file)); // first run: no file Files.writeString(file, "theme=dark\nfontSize=18\n"); System.out.println(load(file)); Files.writeString(file, "theme=dark\nfontSize=big\n"); System.out.println(load(file));
Files.delete(file); Files.delete(folder); }}No settings.properties yet, using defaults Settings[theme=light, fontSize=14] Settings[theme=dark, fontSize=18] Bad fontSize 'big', using 14 Settings[theme=dark, fontSize=14]
What this code does
- A missing file on the first run is normal, so
loadreturns the defaults and says so. Any otherIOExceptionalso falls back, with its type mentioned for the log. - A bad
fontSizefalls back for that one key only; the validtheme=darkis kept.getProperty(key, default)covers a key that is missing from the file.
Fallbacks suit things where a default is harmless and the user can change it later: preferences, colours, page size. They must never hide real data problems. A missing fee amount must not quietly become 0, and missing marks must not become an empty list; those are errors to report.
AccessDeniedException from a file locked on Windows
On Windows, a program that has a file open (such as Excel) can stop other programs from deleting, moving or overwriting it. Java then throws AccessDeniedException or a plain FileSystemException.
Example 4 · Retrying a file locked by another program
import java.io.IOException;import java.nio.file.AccessDeniedException;
// Stands in for Files.move on a file that another program (such as Excel) has openclass LockedFile { private final String name; private final int lockedAttempts; private int tries = 0;
LockedFile(String name, int lockedAttempts) { this.name = name; this.lockedAttempts = lockedAttempts; }
String name() { return name; }
void moveToArchive() throws IOException { tries++; if (tries <= lockedAttempts) { throw new AccessDeniedException(name, null, "file is open in another program"); } System.out.println("Moved " + name + " to archive"); }}
public class LockedFileDemo { static void moveWithRetry(LockedFile file, int maxAttempts) throws IOException { for (int attempt = 1; ; attempt++) { try { file.moveToArchive(); return; } catch (AccessDeniedException e) { System.out.println("Attempt " + attempt + " failed: " + e.getMessage()); if (attempt == maxAttempts) { throw e; } try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw e; } } } }
public static void main(String[] args) { LockedFile[] files = {new LockedFile("report.csv", 2), new LockedFile("fees.xlsx", 99)}; for (LockedFile f : files) { try { moveWithRetry(f, 3); } catch (IOException e) { System.out.println("Gave up. Close " + f.name() + " in other programs (such as Excel) and try again."); } } }}Attempt 1 failed: report.csv: file is open in another program Attempt 2 failed: report.csv: file is open in another program Moved report.csv to archive Attempt 1 failed: fees.xlsx: file is open in another program Attempt 2 failed: fees.xlsx: file is open in another program Attempt 3 failed: fees.xlsx: file is open in another program Gave up. Close fees.xlsx in other programs (such as Excel) and try again.
What this code does
report.csvis locked for a short time, so the third attempt succeeds.fees.xlsxstays locked, so after 3 attempts the loop rethrows andmaingives the user a clear next step.AccessDeniedException(file, other, reason)builds the messagefile: reason. With a real lock, the reason is the Windows text, or the exception is a plainFileSystemExceptionmentioning another process.
Excel with a CSV, an antivirus scan or a backup tool can all hold a file this way. The FileSystemException has a reason saying the file is being used by another process, and AccessDeniedException is its subclass.
AccessDeniedException also appears for a read-only file or a missing permission, which no retry will fix. So retry a few times with a wait, and if it still fails, stop with a message that tells the user what to do: "Close fees.xlsx in other programs (such as Excel) and try again." macOS and Linux usually allow renaming or deleting an open file, so this is mostly a Windows problem.
Next step
Check your understanding
12 quick questions