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.
}
}
}
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
}
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...
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With