This question already has an answer here:
Sonar: How to use try-with-resources to close FileOutputStream
(1 answer)
Closed 5 years ago.
I am having the trouble of close the "FileOutputStream" from sonar . Eventhough I closed the file. From the document of Sonar I donĀ“t understand the error.
I looked at the post
SONAR issue - Close this FileInputStream.
This also not solving my problem.
public void trainL2lSupport(String training_path, String model_path) throws Exception {
BasicConfigurator.configure();
String[] options = { "-s 1" };
FileOutputStream ms = new FileOutputStream(model_path); // This one is producing the error.
classifier.setOptions(options);
logger.info(msg + classifier.globalInfo());
loader.setFile(new File(training_path));
Instances data_set = loader.getDataSet();
data_set.setClassIndex(data_set.numAttributes() - 1);
classifier.buildClassifier(data_set);
Evaluation evaluation = new Evaluation(data_set);
evaluation.crossValidateModel(classifier, data_set, 40, new Random(1));
logger.info(evaluation.toSummaryString());
logger.info(msg1 + timer.stop());
// oos = new ObjectOutputStream(ms);
try {
ObjectOutputStream oos = new ObjectOutputStream(ms);
oos.writeObject(classifier);
oos.flush();
oos.close();
logger.info(msg3+ evaluation.toSummaryString());
logger.info(msg1 + timer.stop());
logger.info("File closed safetly");
} catch(Exception e) {
}
finally {
ms.close();
}
}
How to solve it ?
Use the try-with-resources statement.
If an exception is thrown from any of the lines of code before the try block, the FileOutputStream is never closed. Hence the Sonar warning.
Also, indent your code, don't catch Exception (you should have another warning for that), and don't ignore exceptions like you're doing.
Related
I have recently scanned our code base with Fortify and I'm confused as to why it's flagging certain issues. One issue that I'm facing the issue is with releasing a resource.
Here is a snippet for context.
String someLocation = getPathToTheLocation(); //gives location
try (InputStream in = someLocation == null ? Thread.currentThread().getContextClassLoader()
.getResourceAsStream("someFile.xml") : new FileInputStream(new File(someLocation))) {
/// Do Something
}
Fortify complains that the method that has this try-with-resources block fails to release a system resource allocated by FileInputStream(). Doesn't the try-with-resources help me close the FileInputStream automatically?
Just assuming that Fortify doesn't recognize the try-with-resources paradigm, I refrained from using it and did it the regular way.
String someLocation = getPathToTheLocation(); //gives location
InputStream in = null;
try {
in = someLocation == null ? Thread.currentThread().getContextClassLoader().getResourceAsStream("someFile.xml")
: new FileInputStream(new File(someLocation));
//Do Something.
} finally {
assert in != null;
try {
in.close();
} catch (IOException ioe) {
throw new IllegalStateException("Could not close input stream.", ioe);
}
}
And yet it still complains about the resource being unreleased. What could be the actual issue here that I fail to recognize?
I think everything okay with the code, the problem in Fortify and maybe you should propose an Issue for it. There was quite the same issue with Idea - https://stackoverflow.com/a/34655863/5790043.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
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("Start\tEnd\tDuration");
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
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.
try {..} is not a try-with-resource statement.
Your try{...} may make sense as try-with-resource will close resources for you but not handle exceptions thrown during statements execution of the try block.
But note that a classic try has to be declared with a finally or a catch statement or both.
Your method writeDurationToFile() doesn't throw IOException while you code may throw it.
So you should either add it in the method declaration :
private synchronized void writeDurationToFile(String sFileName, Date dtStartTime, long lDuration, String sStatus) throws IOException
and remove the try{...} to allow the client code to handle the IOException.
Or another way would be catching the exception in the method by completing the try statement with a catch.
In this way, the client code doesn't need to handle the IOException :
try { //classic try
// try-with-resource
try(FileWriter fw = new FileWriter(sFullPath);
PrintWriter pw = new PrintWriter(fw)) {
...
}
...
// other try-with-resource
try(FileWriter fw = new FileWriter(sFullPath, true);
PrintWriter pw = new PrintWriter(fw)) {
...
}
}
// catch exceptions thrown in the block/body of the `try-with-resource` statements
catch (IOException e){
// exception handling
}
As per as my knowledge we use try catch as follows:
try {
//Some code that may generate exception
}
catch(Exception ex) {
}
//handle exception
finally {
//close any open resources etc.
}
But in a code I found following
try(
ByteArrayOutputStream byteArrayStreamResponse = new ByteArrayOutputStream();
HSLFSlideShow pptSlideShow = new HSLFSlideShow(
new HSLFSlideShowImpl(
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(Constants.PPT_TEMPLATE_FILE_NAME)
));
){
}
catch (Exception ex) {
//handel exception
}
finally {
//close any open resource
}
I am not able to understand why this parentheses () just after try.
What is the usage of it? Is it new in Java 1.7? What kind of syntax I can write there?
Please also refer me some API documents.
It is try with Resources syntax which is new in java 1.7. It is used to declare all resources which can be closed. Here is the link to official documentation.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a problem where by a section of my android app works fine on android version 4.1.2 but throws a NullPointerException when the same section is executed on android 4.4.3. My minimum sdk is set to 15 and target sdk is 21. Please find the code below:
try {
FileInputStream towe = new FileInputStream(path2);
re = new BufferedReader(new InputStreamReader(towe));
while ((res = re.readLine()) != null) {
result.append(res);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
re.close(); //ERROR IS GENERATED AT THIS LINE
} catch (IOException e) {
e.printStackTrace();
}
}
Morning guys, been away for a while. It turned out Exception was being thrown because of file path. I had hard-coded the path for android 4.1.2 but in 4.4.3 that path was different even though device was the same. I ended up using the
android.os.Environment.getExternalStorageDirectory();
method. Now working fine on both. Thanks for the suggestions
This is the correct way to write this, from a number of perspectives:
try (FileInputStream towe = new FileInputStream(path2);
Reader re = new BufferedReader(new InputStreamReader(towe))) {
while ((res = re.readLine()) != null) {
result.append(res);
}
}
Use try-with-resources. It is simpler, and more concise.
Don't catch an exception, and continue as if nothing happened. If you find yourself doing this, you are probably catching the exception in the wrong place.
Printing stacktraces in random places is a bad idea.
If you don't use try-with-resources then you need to test that re is non-null in the finally block to avoid the NPE. It would look like this with the erroneous stacktraces and exception squashing removed.
try {
FileInputStream towe = new FileInputStream(path2);
re = new BufferedReader(new InputStreamReader(towe));
while ((res = re.readLine()) != null) {
result.append(res);
}
} finally {
if (re != null) {
re.close();
}
}
And even then, there is a theoretical risk that towe won't be closed. (Hint: Error subclasses.)
NullPointerException on android 4.4.3 but not 4.1.2
What that most likely means is that new FileInputStream(path2); is throwing an exception (probably an IOException of some kind) on one platform and not the other. The clue is most likely in the I/O exception's message.
This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 6 months ago.
I have tried doing this but it always give of an error:
unreported exception IO exception; must be caught or declared to be thrown.
but then if I try putting a try catch in the write, newLine, flush, my main program would have the same error.
public Course(){
try{
fw = new FileWriter("Something.txt", true);
bWrite = new BufferedWriter(fw);
file = new File("Someting.txt");
scanner = new Scanner(file);
}catch(Exception e){}
}
public void setDetails(String cID, String cName)throws Exception{
write = cID + " || " + cName;
bWrite.write(write);
bWrite.newLine();
bWrite.flush();
}
SetDetails() says that it throws an exception. That means wherever we call SetDetails() there needs to be a catch clause.
Also look into chained exceptions.
the answer is to surround the setDetails(); where ever you call it with try and catch like follow:
try{
setDetails("Test","Test");
}catch(Exception e){ //you can leave it blank }
i hope this help you :)