I have a simple servlet where I write to a file if it has a queryparameter ‘hello’, and since this is a test I want to display the error the the webpage also.
IntelliJ is complaining that I am not catching the IOException, not sure what’s wrong:
private static void WriteToFile(String filePath, String fileName, String fileData) {
FileWriter writer = null;
try {
writer = new FileWriter(fileName);
writer.write(fileData);
} catch(IOException ex) {
} finally {
if(writer != null) {
writer.close();
}
}
}
Also, in my exception, I noticed on the web most people write:
How can I output the error to the web page?
You’re not catching
IOExceptionwhen you callwriter.close();in the finally block.You’re also completely swallowing any
IOExceptionthrown in the main code, which is a really bad idea. If something’s goes wrong, you’ll have no idea what’s happening.I would personally suggest that you let that method throw the exception to the caller:
Note that if the
tryblock throws an exception and thefinallyblock does, you’ll effectively “lose” the original exception. You may want to suppress exceptions throw when closing.Or just use Guava which makes all of this simpler anyway with its
Filesclass.Or if you’re using Java 7, you could use a try-with-resources statement.
(I note that you’re ignoring
filePathby the way – why?)