This code uses an API whose result can be used to determine if the operation succeeded or failed. If your code misses a check on the result of the API, you might fail silently. Errors encountered on such failures might be harder to debug.
1private void writeMessageNonCompliant(String dirName, String fileName, String message) {
2 try {
3 File dir = new File(dirName);
4 if (!dir.exists()) {
5 // Noncompliant: code does not handle the case when mkdirs fails.
6 dir.mkdirs();
7 }
8 try (FileOutputStream fos = new FileOutputStream(new File(dir, fileName))) {
9 fos.write(message.getBytes());
10 }
11 } catch (IOException e) {
12 e.printStackTrace();
13 }
14}
1private void writeMessageCompliant(String dirName, String fileName, String message) {
2 try {
3 File dir = new File(dirName);
4 boolean ok = true;
5 if (!dir.exists()) {
6 // Compliant: code handles the case when mkdirs fails.
7 ok = dir.mkdirs();
8 }
9 if (ok) {
10 try (FileOutputStream fos = new FileOutputStream(new File(dir, fileName))) {
11 fos.write(message.getBytes());
12 }
13 } else {
14 log.warn("output directory not created");
15 }
16 } catch (IOException e) {
17 e.printStackTrace();
18 }
19}