when I am reading the code of opentsdb:
try {
System.in.close(); // Release a FD we don't need.
} catch (Exception e) {
log.warn("Failed to close stdin", e);
}
After searching this question on the Internet, I can't find a suitable answer. I don't understand why they write system.in.close(), and I want to know if we don't add this code block, what will happen?
Probably only if you used System.setIn() to override the standard input. One normally does not close the standard input, it's handled by JVM process shutdown.
Related
This question already has answers here:
Returning from a finally block in Java
(6 answers)
Closed 6 years ago.
public boolean sendDeviceEvent() {
boolean status = false;
try {
device.sendEvent("blah...blah");
status = true;
} catch (Exception e) {
log.error("Failed to send NodeLowBattery Event - {} {}", createNodeLowBatteryNotification(), e.getCause());
} finally {
return status;
}
}
I would like to know how the above code can be considered bad practise since it returns from finally.
Based on the byte code information, finally doesn't return abruptly and no values are set in finally. How can this be considered bad ?
The point is: that finally statement simply doesn't make any sense. It adds no value whatsoever to your code. This version:
try {
...
return true;
} catch (...) {
log ...
}
return false;
does the very same; without making you start to think: what is that finally good for?
In other words: don't get too hang up on functionality; and forget about readability. You want to able to understand what is going on as quickly as possible. Using finally will definitely make your "brain cpu" spin "harder" ... just because you have to read it, and then digest and resolve to "ah, actually I don't need that at all".
Of course, this is very subtle; but in the end: a file full of subtle things that could be a bit clearer ... still makes up a file much harder to read than it ought to be!
Finally: don't get me wrong: there might be occasions where returning from the finally block could make sense. But - only when other things happen in that block (meaning there is a real need to have that finally block anyway).
I am using Sonar tool to analyze the coding standard in an existing Application where I met a Sonar Rule: "Close the resources" where Connection's object conn is the culprit.
As we know we should close the Connection object using conn.close(); but in the Application a method to release the connection has been called.
Below is the piece of code where Connection object is closed through a method named releaseConnection() in finally block.
finally {
try {
OtherClass.releaseConnection(conn); // Line: 50 Here is the call to close the conn
}
catch (SomeException se) {
LOGGER.error(" Exception while releaseConnection in add() method : ",se);
}
}
Closing method:
public static void releaseConnection(Connection conn) throws DBException {
if (conn!=null) {
try {
if (!conn.isReadOnly()){
conn.commit();
}
} catch (SQLException e) {
LOGGER.error("Error while commiting the connection. " + e);
rollback(conn);
throw new SomeException(e,SOMETHING);
} finally {
try {conn.close();} catch (SQLException se){
LOGGER.error("releaseConnection() Error " + se);
}
}
}
}
Here's the list of my concern:
As this existing implementation is doing the correct thing (Correct me if I am wrong) is it really need to change the code as per Sonar suggestion.
If really I need to follow the Sonar's suggestion what should be the best way.
UPDATE:
How can I just ignore/bypass some certain code or rule and apply in my above code.
Lets say I want to ignore Line: 50, how can I do that?
I do not want to mess with the above piece of code but I really wanna ignore this and make my issues lesser. Thanks in advance.
You are actually encountering a limitation of the symbolic execution engine (which is used by this rule under the hood) : https://jira.sonarsource.com/browse/SONARJAVA-1591
What is happening here is that we approximate the flow of execution in try/catch/finally by having a path of execution skipping the whole try block (to simplify the handling of flow) and that results in the false positive you mentioned because we don't see the call to your method that would prevent the issue of being raise.
That's right! Sonar does not check if any method is called from finally block to close the resources. It simply checks the closing of resources.
This question already has answers here:
Behaviour of return statement in catch and finally
(8 answers)
Closed 8 years ago.
Similar question has been asked here. But that does not provide answer.
try {
object = (Dev)Class.forName("Dev").newInstance();
} catch (Exception e)
{
throw new RuntimeException("Devis not available");
}
finally
{
return object;
}
But finally block gives warning :
finally block does not complete normally
But as per my understating, finally block always gets executed and will return the object. Why warning says that it will not get completed normally?
The problem is that the finally block would remove any exceptions being thrown since it would issue a "normal" return.
From the JLS spec:
Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.
and (more relevant in your case):
Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.
There are so many explanations about the finally block in a try-catch-finally statement. Go and search for it.
Quick explanation anyway: The finally block is always run, regardless whether an exception was thrown (and maybe caught) or not. If a finally block terminates in an unnormal way (such as itself throwing an excpetion or returning a value) this will always override what was done in the try block or a catch block. That also means that these are got lost.
The conclusion: Never throw an exception ot return a value from the finally block. Only use it for cleaning up processes.
try this. If you are throwing an exception than there is something wrong with object. just return it before the catch.
try {
object = (Dev)Class.forName("Dev").newInstance();
return object;
} catch (Exception e)
{
throw new RuntimeException("Devis not available");
}
Returning from finally is a bad practice in java.
It may result in many unexpected outputs. Check below link for some of such examples:
http://www.cs.arizona.edu/projects/sumatra/hallofshame/
Anyways found few links related to this finally block, Follow the below links for answers related to that.
Does finally always execute in Java?
Returning from a finally block in Java
In my program I have to constantly access the hard drive thousands of times to view images (no way around it), occasionally my program gets tripped up on a "file not found IO Exception" most likely because of the many modifications I'm making to the images and re saving quickly. How do I continue my program even if this error occurs, because currently it causes my program to stop?
Code:
filepattern=imageLocation+temp+"image.jpg";
File outputfile = new File(filepattern);
BufferedImage img = null;
try {
img = ImageIO.read(outputfile);
} catch (IOException e) {
}
Note: I have fixed the problem by making sure the file exists first. Thanks for all your help!
Catch the exception and handle it as needed.
try {
// your code
} catch (<Expected exception> e) {
// handle the exception
}
Surround the statement with a try catch.
This will stop the code from crashing and in the catch block you can write code to deal with the failure.
There are 3 key words
try {}
executes the block that can cause problems
catch (Exception ex) {}
executes code to handle specific exceptions. Instead of Exception you can handle specific exception types
finally {}
executes cleanup code. Even if exception occurs and breaks the execution flow in try block, this code will always execute.
You might try something like the fragment below. Of course, you will want to encapsulate the actual reading in a try / catch / finally block to make sure you close the file
try {
filesTried++;
[you code]
} catch (IOException e) {
fileErrors++;
I'm trying to get this piece of code to work. It's a basic I/O system that copies one file and pastes it into the same directory with the chosen name. It should be simple but for some reason the program runs, it creates the second file but then it gets stuck. The CPU for Java process sits at around 5% and the file is never completed. It only copies over some of the data and then I'd imagine it's stuck in an infinite loop somewhere.
I've already compared my code with the Byte Streams tutorial on the Oracle website.
EXTRA: I just asked it to output what it was reading and it's stuck on an infinite loop reading the value 255. If that helps. Also, I compiled the code directly off the Oracle website and it does the same thing.
It appears consistent from what I can tell. Can anyone tell me what I'm doing wrong? Thank you.
(P.S: I'm Using Eclipse 4.2.0).
This is what I'm doing to copy the file:
package fileIO;
import java.io.*;
import system.Debug;
public class fileUtil {
public static void copyFileTo(String file2Copy, String file2Paste) {
FileInputStream fin = null;
FileOutputStream fout = null;
try {
fin = new FileInputStream(file2Copy);
fout = new FileOutputStream(file2Paste);
int aByte;
while ((aByte = fin.read()) != -1) {
fout.write(aByte);
}
} catch (FileNotFoundException e) {
Debug.out("Error: File Not Found: " + file2Copy);
} catch (IOException e) {
Debug.out("Error: File IO Exception Copying: " + file2Copy);
} catch (Exception e) {
Debug.out("Error: General Exception Closing Streams:" + file2Copy);
} finally {
try {
fin.close();
fout.close();
} catch (IOException e) {
Debug.out("Error: File IO Exception Closing Streams: " + file2Copy);
} catch (Exception e) {
Debug.out("Error: General Exception Closing Streams:" + file2Copy);
}
}
}
}
In my program main class I run this:
fileUtil.copyFileTo("google.bmp", "google(1).bmp");
Try to do fout.flush() before you close the OutputStream.
Okay, so I found out what was happening. Was a really nooby mistake.
I'll put my pride aside encase anyone else has this problem. It's not an infinite loop, it's just that copying using ByteStreams takes AGES. I was expecting a fast result from small image files but even small image files take a long long time to copy. I let it run for 30 seconds and the program terminated properly and I got my image copy just fine.
Thank god it's solved, I was beginning to worry.
... or do not invent bother re-inventing the wheel: use FileUtils.copyFile from the proven Apache commons-io which does it in one line.
(beware: this comment is not as innocent as it seems: File.rename does not work well on Windows shares - commons-io is always the safe bet to do these things)
Edit
Stackoverflow is not a goog place for "homework" - or you must at least say so. It is not that your problem is not real. It is that your objectives differ: you want to learn something, we want to make it work reliably with minimum maintenance.
...which leads to my second point: when you are in professional life, never program this again. As you discovered, even if you make it work, it may be extremely inefficient, handle errors incorrectly, etc.. This is particularly true with IO which is always more tricky than it seems.
Finally, since I gave you a link to a well trusted library under Apache 2.0 license, maybe you could have had a look at the source code ?