Skip to lesson

Retry and recover from file errors

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

ClassifyDemo.javaJava
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);        }    }}
Output
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

  • NoSuchFileException is also a FileSystemException, but its reason is null, so it is treated as permanent. The AccessDeniedException check 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.

Flow of a retry loop. Try the operation. If it worked, you are done. If not, ask whether the error is temporary and attempts are left. If yes, wait (200 ms, then 400 ms) and try again. If no, give up with a fallback value or a clear message.

Example 2 · A retry loop with a limit and backoff

RetryDemo.javaJava
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());        }    }}
Output
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

  • retry tries the action up to maxAttempts times. 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.
  • IoAction is a small functional interface whose method may throw IOException, so method references like RetryDemo::readMarks fit. An interrupt during sleep ends the retries with an InterruptedIOException.

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

public class RetryTrace {
static int calls = 0;
static String readReport() {
calls++;
if (calls < 3) {
throw new IllegalStateException("file is in use");
}
return "report ok";
}
public static void main(String[] args) throws InterruptedException {
int maxTries = 3;
for (int i = 1; i <= maxTries; i++) {
try {
System.out.println(readReport());
break;
} catch (IllegalStateException e) {
System.out.println("Attempt " + i + " failed: " + e.getMessage());
Thread.sleep(200L * i);
}
}
}
}

Variables

maxTries
3
calls
0

Output

(nothing printed yet)

Line 13At most three attempts. calls counts how often readReport has run.

Step 1 of 16
Only retry operations that are safe to repeat. Reading a file is; adding a fee payment to a list twice is not.

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

FallbackDemo.javaJava
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);    }}
Output
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 load returns the defaults and says so. Any other IOException also falls back, with its type mentioned for the log.
  • A bad fontSize falls back for that one key only; the valid theme=dark is 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

LockedFileDemo.javaJava
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.");            }        }    }}
Output
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.csv is locked for a short time, so the third attempt succeeds. fees.xlsx stays locked, so after 3 attempts the loop rethrows and main gives the user a clear next step.
  • AccessDeniedException(file, other, reason) builds the message file: reason. With a real lock, the reason is the Windows text, or the exception is a plain FileSystemException mentioning 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.

The examples simulate the lock, because a real one needs a second program holding the file open.

Next step

Check your understanding

12 quick questions