I'm calling a method to write some data to a CSV file in java. Inside that method, I'm using a FileWriter that throws an IOException. I'm wondering what the correct way to handle this exception is if I want to handle it in the outer method while also ensuring that the FileWriter gets closed.
I am thinking of two solutions:
Just handle the exception inside the method that opens the FileWriter.
Figure out a way to pass the FileWriter back to the calling method so that it may be closed.
Here's an example of what I'm talking about:
public static void outerFunc() {
// get some sort of data
try {
innerFunc(data);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
// can I close the FileWriter here somehow?
}
}
private static void innerFunc(Data data) throws IOException {
FileWriter csv = new FileWriter("result.csv")
// Write the data to the file
csv.flush();
csv.close();
}
Let me know what you guys think. I'm very open to the fact that I may be completely off base here and should be doing this a different way. Thank you in advance for any input!
The method that opens the resource should close it, and I would use the try-with-resources
Statement. Like,
try (FileWriter csv = new FileWriter("result.csv")) {
// ...
}