'Null Dereference Fortify Issue
I'm working on remediating fortify findings within a code base and the scan came back with a null dereference finding. The recommendation is that I add a null check to csvWriter, but to be honest I don't exactly know what that means. Could anybody point me in the right direction? Thanks.
private void writeBadRecordFile() {
CsvWriter csvWriter = null;
try {
badRecordFile = File.createTempFile("BadRecords", ".csv");
badRecordFile.deleteOnExit();
FileWriter writer = new FileWriter(badRecordFile);
csvWriter = new CsvWriter(writer, ',');
String[] header = {"BIC"};
csvWriter.writeRecord(header);
for (String badRecord : badRecords) {
csvWriter.write(badRecord);
csvWriter.endRecord();
}
csvWriter.flush();
} catch (IOException e) {
errorMessage = "Bad records were detected in the uploaded file, but the bad record file was not able to be created.";
e.printStackTrace();
} finally {
csvWriter.close();
}
}
Solution 1:[1]
If the first three lines of your try block fail, then csvWriter is still null, and the finally block which runs csvWriter.close will throw NullPointerException. The linter is recommending that you do
if (csvWriter != null) {
csvWriter.close();
}
in your finally block. Or, better, use Java's try-with-resources statement to forgo the problem entirely.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silvio Mayolo |
