I agree with the other answers as to the problem (the Scanner
can throw an exception if it can't find the file). I haven't seen what I'd consider the correct solution though.
String[] users = new String[6];
int index_counter = 0;
File credentials_file = new File("credentials.txt");
try (Scanner file_reader = new Scanner(credentials_file)) {
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
index_counter++;
}
} catch (FileNotFoundException e) {
// handle exception
} catch (NoSuchElementException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
}
The try-with-resources statement will automatically close the Scanner
for you. This will work with any class that implements the AutoCloseable
interface.
And in this case, it puts the statement within the scope of the try
, so exceptions will be caught.
Your exception handling is questionable, so I didn't include it. But that's not really the point here. You can read more about Best Practices to Handle Exceptions in Java or How to Specify and Handle Exceptions in Java.
There is an argument that you should let the exception bubble up to the caller. This answer describes how to do that. But in this case, the caller doesn't really know how to handle a FileNotFoundException
, because it doesn't know anything about the file. The file is defined in this method.
You could throw a different, more explanatory exception. Or you could handle the exception here by explaining what a credentials.txt
is. Or fail over to a default. Or just log the exception, although that's questionable. If you do that, you should explain (in a comment) why that is sufficient.
I added a line to increment index_counter
just because it seemed to be missing.
See also