I have the following code which yields me a “Syntax error, insert “Finally” to complete TryStatement”.
private synchronized void writeDurationToFile(String sFileName, Date dtStartTime, long lDuration, String sStatus) { if(!sRHTimeStamp.isEmpty()) { String sFullPath = sFileName + "_" + sRHTimeStamp + ".csv"; try { if(!Paths.get(sFullPath).toFile().exists()) { try( FileWriter fw = new FileWriter(sFullPath); PrintWriter pw = new PrintWriter(fw);) { pw.println("StarttEndtDuration"); pw.println(TimeUtils.getTimeStamp(true, dtStartTime) + "," + lDuration + "," + sStatus); } }else{ try(FileWriter fw = new FileWriter(sFullPath, true); PrintWriter pw = new PrintWriter(fw);) { pw.println(TimeUtils.getTimeStamp(true, dtStartTime) + "," + lDuration + "," + sStatus); } } } //Here I get the error notification } }
Why do I get this error, and how can I write it better to eliminate the duplication of
pw.println(TimeUtils.getTimeStamp(true, dtStartTime) + "," + lDuration + "," + sStatus);
but still use the “try-with-resource” implementation.
I based my code on http://tutorials.jenkov.com/java-exception-handling/try-with-resources.html
Advertisement
Answer
Your larger try
block is not a try-with-resources, but rather a standard try. It therefore needs to have either a catch
or finally
block added to it.