Reputation: 3
The goal of the method below is to open a file and set a List of Strings equal to its lines before returning the List. If the file cannot be opened or read for whatever reason, I want to print the message, "Error reading ''..."
static List<String> readFile (String filename) {
System.out.println("Opening file \'" + filename + "\'...\n");
List<String> lines = null;
try {
Charset charset = Charset.forName("ISO-8859-1");
lines = Files.readAllLines(Paths.get(filename), charset);
}
finally {
catch (IOException e) {
System.out.println("Error reading \'" + filename + "\'...");
}
return lines;
}
I am executing the program in the Windows 10 command line with the file name as an argument. It works, but, in addition to my error message, another message is displayed to the console (by the JVM?). This is the command and output:
C:>java FileIO fake.txt
Opening file 'fake.txt'...
Error reading 'fake.txt'...fake.txt
Exception in thread "main" java.lang.NullPointerException
at FileIO.display(FileIO.java:35)
at FileIO.main(FileIO.java:14)
I am new to both Java and the Windows command line. I have some experience with C++ and Python in Linux terminals.
Is it possible to keep these messages from printing to the console or a different way to handle a bad file from the user? My understanding is that Files.readAllLines() requires the IOException.
I don't understand why the default is to assume the developer wouldn't create error messages to be displayed to the user. Or is the assumption that users don't run console applications and the only people who would see these exceptions are developers?
Upvotes: 0
Views: 93
Reputation: 533740
The problem is that you are catching the exception and pretending it didn't matter that it happened, i.e. you continue with a null
value and try to display it when clearly that's not going to work.
You should only catch an exception when you are ready to deal with it. i.e. in the calling method.
public static void main(String... args) {
try {
List<String> lines = readFile(args[0]);
// don't try to display the lines of a file if it failed with an IOException
display(lines);
} catch(IOException ioe) {
System.err.println("Cannot display file " + ioe);
}
}
When you get an error, you should print out what it is as the error might be telling you something useful.
Note: this would be the best way to handle an exception even in C++.
Upvotes: 1