How do you loop a try/catch statement? I'm making a program that is reading in a file using a Scanner and it's reading it from the keyboard. So what I want is if the file does not exist, the program will say "This file does not exist please try again." then have the user type in a different file name. I have tried a couple different ways to try an do this but, all of my attempts end up with the program crashing.
Here is what I have
try {
System.out.println("Please enter the name of the file: ");
Scanner in = new Scanner(System.in);
File file = new File(in.next());
Scanner scan = new Scanner(file);
} catch (Exception e) {
e.printStackTrace();
System.out.println("File does not exist please try again. ");
}
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:
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.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 ...
Instead of using a try catch block, try a do while
loop checking if the file exists.
do {
} while ( !file.exists() );
This method is in java.io.File
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