If you want to try again after a failure, you need to put this code inside the loop; for example something like this:
boolean done = false; while (!done) { try { ... done = true; } catch (...) { } }
(A do-while is a slightly more elegant solution.)
However, in this context, BAD PRACTICE will catch an Exception . It will catch not only those exceptions that you expect (e.g. IOException ), but also unexpected ones, such as NullPointerException , etc., which are signs of an error in your program.
Best practice is to catch the exceptions you expect (and can handle) and let other people propagate. In your particular case, catching a FileNotFoundException . (This is what the Scanner(File) constructor declares.) If you did not use Scanner for input, you may need an IOException instead.
I have to fix a serious mistake in the voting answers.
do { .... } while (!file.exists());
This is not true because checking for a file is not enough:
- the file may exist, but the user does not have permission to read it,
- a file may exist, but be a directory,
- the file may exist but be inaccessible due to a hard disk error or similar
- the file can be deleted / disconnected / renamed between the
exists() test and the subsequent attempt to open it.
Note that:
File.exists() ONLY checks that the file system object exists with the specified path, and not that it is actually a file or that the user has access to it for reading or writing.- It is not possible to check whether the I / O operation is completed due to hard disk errors, network drive errors, etc.
- There is no solution to the problem with an open or unrelated / renamed race. Although this is rare in normal use, this error can be targeted if the file in question is security critical.
The correct approach is to simply try to open the file and catch and handle an IOException if that happens. It is simpler and more reliable, and probably faster. And for those who would say that exceptions should not be used for "normal flow control", this is not normal flow control ...
source share