If you want to retry after a failure, you need to put that code inside a loop; e.g. something like this:
boolean done = false;
while (!done) {
try {
...
done = true;
} catch (...) {
}
}
(A do-while is a slightly more elegant solution.)
However, it is BAD PRACTICE to catch Exception
in this context. It will catch not only the exceptions that you are expecting to happen (e.g. IOException
), but also unexpected ones, like NullPointerException
and so on that are symptoms of a bug in your program.
Best practice is to catch the exceptions that you are expecting (and can handle), and allow any others to propagate. In your particular case, catching FileNotFoundException
is sufficient. (That is what the Scanner(File)
constructor declares.) If you weren't using a Scanner
for your input, you might need to catch IOException
instead.
I must correct a serious mistake in the top-voted answer.
do {
....
} while (!file.exists());
This is incorrect because testing that the file exists is not sufficient:
- the file might exist but the user doesn't have permission to read it,
- the file might exist but be a directory,
- the file might exist but be unopenable due to hard disc error, or similar
- the file might be deleted/unlinked/renamed between the
exists()
test succeeding and the subsequent attempt to open it.
Note that:
File.exists()
ONLY tests that a file system object exists with the specified path, not that it is actually a file, or that the user has read or write access to it.- There is no way to test if an I/O operation is going to fail due to an hard disc errors, network drive errors and so on.
- There is no solution to the open vs deleted/unlinked/renamed race condition. While it is rare in normal usage, this kind of bug can be targeted if the file in question is security critical.
The correct approach is to simply attempt to open the file, and catch and handle the IOException
if it happens. It is simpler and more robust, and probably faster. And for those who would say that exceptions should not be used for "normal flow control", this isn't normal flow control ...