Reputation: 19
I have a question regarding FileNotFoundExcpetion. The interface I have got defined the method name including "throws FileNotFoundExcpetion".
public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {
try {
FileWriter writer = new FileWriter(filename);
for (String str : assignment) {
writer.write(str + "\n");
}
writer.close();
} catch (IOException e) {
System.err.print("Something went wrong");
}
}
Is this the right way to handle the exception? When I am writing to a file I am creating with the filewriter, how is it possible that the file wouldnt be found if I am creating the file in the method??
Upvotes: 1
Views: 9043
Reputation: 1207
You can catch Exception instead of IOException
public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {
try {
FileWriter writer = new FileWriter(filename);
for (String str : assignment) {
writer.write(str + "\n");
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
From this type coding, you can see/learn the hierarchy of exceptions. If you want to execute your program whether caught exception or not, you can use finally block. Where you will close your writer.
Upvotes: 0
Reputation: 1202
IOException
is a super class of FileNotFoundException
. Therefore your catch block for IOException
also catches every FileNotFoundException
.
You should implement the function as follows:
public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {
try (FileWriter writer = new FileWriter(filename)) {
for (String str : assignment) {
writer.write(str + "\n");
}
} catch (FileNotFoundException e) {
throw e; // catch and re-throw
} catch (IOException e) {
System.err.print("Something went wrong");
}
}
Upvotes: 3