Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to try a method again after a exception has been handled?

Tags:

java

exception

I am new to exceptions, haven't covered them in college yet so still learning about them. I tried this and it seems to work, but doesn't seem "right". What's the correct way to try a method again after a exception has been handled?

public static void openCSV(String file) {
    FileInputStream fis;

    try {
        fis = new FileInputStream(file);
    } catch (FileNotFoundException e) { //fnf, probably not downloaded yet.

        downloadCSV(file); //Download it and try again.

        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            // OK, something else is the problem.
        }
    }
}
like image 644
ArturPhilibin Avatar asked Dec 11 '25 04:12

ArturPhilibin


2 Answers

Your question is not per se about "exceptions", but is more about design in general. You'll get many, many opinions about the right way to handle this.

The most obvious fix is

if (!new File(file).exists()) {
    downloadCSV(file);
}
try {
    fis = new FileInputStream(file);
} catch (IOException e) {
    // scream
}
like image 140
Jonathan Feinberg Avatar answered Dec 12 '25 16:12

Jonathan Feinberg


This is a form of exception misuse. If sometimes the file must be downloaded, you shouldn't rely on an exception to tell you so.

Try something like this:

public static void openCSV(String file) {
    FileInputStream fis;

    try {
        if (!(new File(file).exists())) {
            downloadCSV(file); //download it
        }
        fis = new FileInputStream(file);
        // should probably use the stream here, so you can close it in a finally clause linked to this try clause...
    } catch (FileNotFoundException e) { //file doesnt exist
        // Re-throw as a declared exception, a RuntimeException, and/or log it...
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ioe) {
                // write exception to logs or take other appropriate action...
            }
        }
    }
}
like image 31
Drew Wills Avatar answered Dec 12 '25 18:12

Drew Wills