I get a critical error with findbugs:
The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed.
try {
...
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
...
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (stdError != null) {
stdError.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Do I need to close InputStreamReader also or p.getErrorStream (it returns InputStream)?
What happens when an exception is thrown while creating the BufferedReader object? The stream managed by the InputStreamReader object is not closed until some time in the future when the garbage collector decides to destroy the object.
You will likely have similar problems if an exception is thrown while creating the InputStreamReader object.
BufferedReader and InputStreamReader both close the underlying stream when they are closed. You should be fine by closing stdError
Related
I don't know how to understand this:
{
if (inputStream **!= null**) {
inputStream.close();
from that example:
public class CopyLines {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}}
inputStream is beeing closed when there is any data provided???
It means that whenever the try block is completed (successfully or not) it will try to close the streams (inputStream and outputStream) in the finally block but as the try block could fail while creating the instance of BufferedReader or PrintWriter, you need to check first if it is not null otherwise you will get a NPE.
You can consider using try-with-resouces statement to avoid having to check if null and calling close() explicitly such that it would simplify your code a lot.
try (BufferedReader inputStream = new BufferedReader(new FileReader("xanadu.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("characteroutput.txt")) {
// your code here
}
If you're asking why this code is in finally block, then,
This is simply to ensure that the inputStream and outputStream will always be closed, no matter whether the code above encounters or doesn't encounters an exception.
How is it different.
The difference is during any exception. If any exception occurs, then instead of simply returning, it will ensure that both the streams are closed before returning the exception to the method that called this method.
bacause java's finally block is always executed, unless:
System.exit is called
or JVM crashes
This is a common practice to close stream, database, or any other similar connections in finally blocks. This ensures that the connections are always closed. Because if they aren't in finally block, and system is continuously encountering some or the other Excpetion then it will eventually run out of connections.
That's just to avoid null pointer exception. The functions are called only when object is not null.
In simple words, close function is only called when the objects are not null else if you call close() on object with null value, you will come across null pointer exception.
Interesting thing is the usage of finally, which is always called whether there is any exception or not.
When the execution reaches the finally block, it is first checked inputstream and outputstream are null or not then both the streams are closed to free the resources.
Please refer the link to check about try with finally : https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is there a "best practice" for how much code to put inside a try/catch block?
I have posted 3 different scenarios below.
I did not include behavior in each catch block and i did not include the finally block. This was to improve readability for viewers. Assume each catch does something differently. And assume the finally will be closing the stream. Just trying to create an easy to read example for future readers.
Control, no try/catch.
Code with 1 try/catch for each place needed.
Code with only 1 try/catch surrounding whole code block.
What is generally accepted as the best practice and why?
Scenario 1
Code without try/catch, just for control.
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
bufferedReader.close();
Scenario 2
Code with a try/catch block for each individual place needed.
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("somepath"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
Scenario 3
Code with 1 try/catch surrounding the whole block of code.
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should scope your try/catches based on the following criteria:
do you need to do different things based on where the exception came from?
do you need to do different things based on which exception was thrown?
what code needs to be skipped (aka is "invalid") when a given exception is thrown?
answering these questions will enable you to determine the appropriate scope for any try/catch block.
I'd put as little in the try-catch as possible.
This allows you to very easily move pieces of code into separate methods which is a good coding practice (obeying single responsibility principle; see the book "Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin).
Another advantage is that you can quickly identify which code actually can throw an exception.
Scenario 2 seems a bit extreme though, and since the method is pretty small, Scenario 3 seems like the best choice.
However, you need to have your "close" statement in a finally block.
This is a matter of opinion. I've seen each of these patterns a lot.
Pattern 1 is only good when your method can throw the excpetions and have something up the caller chain handle that. That is often desireable. However, since the close call is not in a finally block, it might not be called. At least, use a try-finally block.
Pattern 2 isn't good, since if the first try-catch block handles an exception, the rest of the method is useless.
Pattern 3 is okay, but not great, as printing stack traces hides the fact that the operation failed. What will the caller do if it thinks the operation occurred when it didn't. Also, the closes might not have happened, which can lead to program failure.
In pseudo code, this variant of pattern 3 is better:
Declare Streams, connections, etc.
try
Initialize streams, connections, etc,
Do work.
catch (optional)
Catch and handle exceptions.
Do not simply log and ignore.
finally
Close connections and streams in reverse order.
Remember, closing these objects can throw,
so catch exceptions the close operation throws.
End.
If you are using Java 7, use try-with-resources:
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
}
Have IOExceptions bubble up to the caller.
You should go with the third scenario.
If the bufferedReader hits an exception then on creation in the second scenario then it you try to readLine() on it, it will hit another exception. No point in raising multiple exceptions for the same problem.
You should also close your bufferedReader in the finally block.
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
I consider an Exception being an uncoditionally returned result type. So when I work with try-catch sections, I'm trying to answer questions
Should I handle an unexpected result here or should I propagate it on a higher level?
Which unexpected results should I handle?
How to handle them?
In 95% of the cases I don't go further than the first point, so I just propagate the errors.
For file processing I use try-with-resources an re-throw the IOException with throw new RuntimeException(e).
I think it's similar with how much code to put in method. Try to write try/catch/finally which takes no more than one screen. I want to say it's not a problem to wrap entire method body into try{} block, but you should separate this code into several methods if it became too long.
You example with one try/catch each doesn't make sense because you just print a stack trace and continue - knowing already that it will be a failure. You might as well try/catch the whole lot, or add throws SomeException to the method signature and let the calling method decide what went wrong.
Also, don't worry about squeezing too much inside a try/catch. You can always extract that code into another method. Readability is one of the single most important aspects of programming.
The third option is certainly best. You don't want your try/catch block to become unwieldy, but in this example, it is short enough that you do not need to divide it as you have done in your second option.
Not scenario 2. If the FileReader or BufferedReader constructor throws, then bufferedReader will be null but the next try/catch will still execute. Therefore you'll get an (uncaught) exception at bufferedReader.readLine -- a NullPointerException. Between scenarios 1 and 3, I generally like 3 more because it doesn't require the caller to catch. BTW, you don't need to catch FileNotFoundException explicitly, because it inherits from IOException and therefore that catch block will catch both.
jtahlborn already has the correct answer.
Unfortunately sometimes, proper exception handling can be pretty bloated.
One should be ready to deal with it, if required.
Another possible scenario are nested try-catch blocks.
Consider:
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
try {
this.doSomething(object);
} catch (InvalidArgumentException iae) {
throw new RuntimeErrorException("Failed to process line " + line + ", iae);
} catch (ParserWarning e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
bufferedReader.close();
}
try {
bufferedReader = new BufferedReader(new FileReader(new File(file,FILENAME)));
String readLine = bufferedReader.readLine();
//do stuff
} catch(Exception e) {
throw e;
} finally {
if (bufferedReader!=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
will the bufferedReader closing be invoked in any case in this code?
yes it invokes in any case( if it is not null in you case).According to java docs
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
If you are using Java7 then I strongly recommond to use try-with-resources Statement.Then you do not require to write the finally block in your code.
try-with-resouce example
try (BufferedReader bufferedReader =
new BufferedReader(new FileReader(new File(file,FILENAME)));) {
String readLine = bufferedReader.readLine();
//do stuff
} catch(Exception e) {
throw e;
}
Note:
finally block won't execute in only one case. That is when JVM shutdown(generally with System.exit() statement or when the JVM process is killed externally). In all other cases the finally is guaranteed to execute
Finally is always executed, even if the exception is thrown or not. So it will execute the bufferedReader.close(); when bufferedReader is not null
I would refer you to this question:
In Java, is the "finally" block guaranteed to be called (in the main method)?
Basically, the finally block will always get run, with one exception: If the JVM exits before the finally block executes.
As to whether the bufferedReader executing - as written, so long as it's not null, yes, with the above noted exception
Yes, this code will close bufferedReader in any situation. But in general the code looks like a mess. Java 7 try-with-resources is the best solution of closing resources
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(file,FILENAME))) {
//do stuff
}
finally in a try/catch block means that it will happen no matter what.
Also, the exception would be better stated as IOException.
There is really no reason to have a catch block throw an exception in this situation.
Note: It is true that invoking System.exit() will terminate your could as soon as it is encountered and will result in the application being terminated by the JVM (Java Virtual Machine).
I'm writing an app that connect to a website and read one line from it. I do it like this:
try{
URLConnection connection = new URL("www.example.com").openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = rd.readLine();
rd.close();
}catch (Exception e) {
//exception handling
}
Is it good? I mean, I close the BufferedReader in the last line, but I do not close the InputStreamReader. Should I create a standalone InputStreamReader from the connection.getInputStream, and a BufferedReader from the standalone InputStreamReader, than close all the two readers?
I think it will be better to place the closing methods in the finally block like this:
InputStreamReader isr = null;
BufferedReader br = null;
try{
URLConnection connection = new URL("www.example.com").openConnection();
isr = new InputStreamReader(connection.getInputStream());
br = new BufferedReader(isr);
String response = br.readLine();
}catch (Exception e) {
//exception handling
}finally{
br.close();
isr.close();
}
But it is ugly, because the closing methods can throw exception, so I have to handle or throw it.
Which solution is better? Or what would be the best solution?
The general idiom for resource acquisition and release in Java is:
final Resource resource = acquire();
try {
use(resource);
} finally {
resource.release();
}
Note:
try should immediately follow the acquire. This means you can't wrap it in the decorator and maintain safety (and removing spaces or putting things on one line doesn't help:).
One release per finally, otherwise it wont be exception safe.
Avoid null, use final. Otherwise you'll have messy code and potential for NPEs.
Generally there is no need to close the decorator unless it has a further resource associated with it. However, you will generally need to flush outputs, but avoid that in the exception case.
The exception should either be passed through to the caller, or caught from a surrounding try block (Java leads you astray here).
ou can abstract this nonsense with the Execute Around idiom, so you don't have to repeat yourself (just write a lot of boilerplate).
Closing the BufferedReader is enough - this closes the underlying reader too.
Yishai posted a nice pattern for closing the streams (closing might throw another exception).
Is it good? I mean, I close the BufferedReader in the last line, but I do not close the InputStreamReader.
Apart from the fact that it should be done in the finally (so that the close is ensured, even in case of an exception), it's fine. The Java IO classes uses the decorator pattern. The close will be delegated to the underlying streams.
But it is ugly, because the closing methods can throw exception, so I have to handle or throw it.
When the close throws an exception, it often just means that the other side has been closed or deleted, which is completely out of your control. You can at highest log or ignore it. In a simple application I would just ignore it. In a mission critical application I would log it, just to be sure.
In a nut, your code can be rewritten as:
BufferedReader br = null;
try {
URLConnection connection = new URL("www.example.com").openConnection();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = br.readLine();
}catch (Exception e) {
//exception handling
}finally{
if (br != null) try { br.close(); } catch (IOException ignore) {}
}
In Java 7 there will be automatic resource handling which would made your code as concise as:
try (BufferedReader br = new InputStreamReader(new URL("www.example.com").openStream())) {
String response = br.readLine();
} catch (Exception e) {
//exception handling
}
See also:
Java IO tutorial
C# "using" keyword in Java
How to use URLConnection
BufferedReader br = null;
You are declaring a variable without assigning it (null doesn't count - it is a useless assignment in this case). This is a code "smell" in Java (ref Effective Java; Code Complete for more on variable declaration).
}finally{
br.close();
isr.close();
}
First, you only need to close the top-most stream decorator (br will close isr). Secondly, if br.close() threw an exception, isr.close() would not be called, so this is not sound code. Under certain exception conditions, your code will hide the originating exception with a NullPointerException.
isr = new InputStreamReader(connection.getInputStream());
If the (admittedly unlikely) event that the InputStreamReader constructor threw any kind of runtime exception, the stream from the connection would not be closed.
Make use of the Closeable interface to reduce redundancy.
Here is how I would write your code:
URLConnection connection = new URL("www.example.com").openConnection();
InputStream in = connection.getInputStream();
Closeable resource = in;
try {
InputStreamReader isr = new InputStreamReader(in);
resource = isr;
BufferedReader br = new BufferedReader(isr);
resource = br;
String response = br.readLine();
} finally {
resource.close();
}
Note that:
no matter what kind of exception is thrown (runtime or checked) or where, the code does not leak stream resources
there is no catch block; exceptions should be passed up to where the code can make a sensible decision about error handling; if this method was the right place, you'd surround all of the above with try/catch
A while back, I spent some time thinking about how to avoid leaking resources/data when things go wrong.
I think it will be better to place the
closing methods in the finally block
Yes, always. Because an exception might occur and resources aren't released/closed properly.
You only need to close the most outer reader because it will be responsible for closing any enclosing readers.
Yes, it's ugly... for now. I think there are plans for an automatic resource management in Java.
I'd use apache commons IO for this, as others have suggested, mainly IOUtils.toString(InputStream) and IOUtils.closeQuietly(InputStream):
public String readFromUrl(final String url) {
InputStream stream = null; // keep this for finally block
try {
stream = new URL(url).openConnection().getInputStream(); // don't keep unused locals
return IOUtils.toString(stream);
} catch (final IOException e) {
// handle IO errors here (probably not like this)
throw new IllegalStateException("Can't read URL " + url, e);
} finally {
// close the stream here, if it's null, it will be ignored
IOUtils.closeQuietly(stream);
}
}
You don't need multiple close statements for any of the nested streams and readers in java.io. It's very rare to need to close more than one thing in a single finally - most of the constructors can throw an exception, so you would be trying to close things you haven't created yet.
If you want to close the stream whether or not the read succeeds, then you need to put in into a finally.
Don't assign null to variables and then compare them to see whether something happened earlier; instead structure your program so the path where you close the stream can only be reached if the exception is not thrown. Apart from the variables used to iterate in for loops, variables should not need to change value - I tend to mark everything final unless there is a requirement to do otherwise. Having flags around your program to tell you how you got to the code currently being executed, and then changing behaviour based on those flags, is very much a procedural (not even structured) style of programming.
How you nest the try/catch/finally blocks depends on whether you want to handle the exceptions thrown by the different stages differently.
private static final String questionUrl = "http://stackoverflow.com/questions/3044510/";
public static void main ( String...args )
{
try {
final URLConnection connection = new URL ( args.length > 0 ? args[0] : questionUrl ).openConnection();
final BufferedReader br = new BufferedReader ( new InputStreamReader (
connection.getInputStream(), getEncoding ( connection ) ) );
try {
final String response = br.readLine();
System.out.println ( response );
} catch ( IOException e ) {
// exception handling for reading from reader
} finally {
// br is final and cannot be null. no need to check
br.close();
}
} catch ( UnsupportedEncodingException uee ) {
// exception handling for unsupported character encoding
} catch ( IOException e ) {
// exception handling for connecting and opening reader
// or for closing reader
}
}
getEncoding needs to inspect the results of the connection's getContentEncoding() and getContentType() to determine the encoding of the web page; your code just uses the platform's default encoding, which may well be wrong.
Your example though is unusual in structured terms, since it is very procedural; normally you would separate the printing and the retrieving in a larger system, and allow the client code to handle any exception (or sometimes catch and create a custom exception):
public static void main ( String...args )
{
final GetOneLine getOneLine = new GetOneLine();
try {
final String value = getOneLine.retrieve ( new URL ( args.length > 0 ? args[0] : questionUrl ) );
System.out.println ( value );
} catch ( IOException e ) {
// exception handling for retrieving one line of text
}
}
public String retrieve ( URL url ) throws IOException
{
final URLConnection connection = url.openConnection();
final InputStream in = connection.getInputStream();
try {
final BufferedReader br = new BufferedReader ( new InputStreamReader (
in, getEncoding ( connection ) ) );
try {
return br.readLine();
} finally {
br.close();
}
} finally {
in.close();
}
}
As McDowell pointed out, you may need to close the input stream if new InputStreamReader throws.
In scope of Java 8 I would use alike:
try(Resource resource = acquire()) {
use(resource);
reuse(resource);
}
Wrote up a basic file handler for a Java Homework assignment, and when I got the assignment back I had some notes about failing to catch a few instances:
Buffer from file could have been null.
File was not found
File stream wasn't closed
Here is the block of code that is used for opening a file:
/**
* Create a Filestream, Buffer, and a String to store the Buffer.
*/
FileInputStream fin = null;
BufferedReader buffRead = null;
String loadedString = null;
/** Try to open the file from user input */
try
{
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
fin.close();
}
/** Catch the error if we can't open the file */
catch(IOException e)
{
System.err.println("CRITICAL: Unable to open text file!");
System.err.println("Exiting!");
System.exit(-1);
}
The one comment I had from him was that fin.close(); needed to be in a finally block, which I did not have at all. But I thought that the way I have created the try/catch it would have prevented an issue with the file not opening.
Let me be clear on a few things: This is not for a current assignment (not trying to get someone to do my own work), I have already created my project and have been graded on it. I did not fully understand my Professor's reasoning myself. Finally, I do not have a lot of Java experience, so I was a little confused why my catch wasn't good enough.
Buffer from file could have been null.
The file may be empty. That is, end-of-file is reach upon opening the file. loadedString = buffRead.readLine() would then have returned null.
Perhaps you should have fixed this by adding something like if (loadedString == null) loadedString = "";
File was not found
As explained in the documentation of the constructor of FileInputStream(String) it may throw a FileNotFoundException. You do catch this in your IOException clause (since FileNotFoundException is an IOException), so it's fine, but you could perhaps have done:
} catch (FileNotFoundException fnfe) {
System.err.println("File not fonud!");
} catch (IOException ioex {
System.err.println("Some other error");
}
File stream wasn't closed
You do call fin.close() which in normal circumstances closes the file stream. Perhaps he means that it's not always closed. The readLine could potentially throw an IOException in which case the close() is skipped. That's the reason for having it in a finally clause (which makes sure it gets called no matter what happens in the try-block. (*)
(*) As #mmyers correctly points out, putting the close() in a finally block will actually not be sufficient since you call System.exit(-1) in the catch-block. If that really is the desired behavior, you could set an error flag in the catch-clause, and exit after the finally-clause if this flag is set.
But what if your program threw an exception on the second or third line of your try block?
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
By this point, a filehandle has been opened and assigned to fin. You could trap the exception but the filehandle would remain open.
You'll want to move the fin.close() statement to a finally block:
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e2) {
}
}
Say buffRead.readLine() throws an exception, will your FileInputStream ever be closed, or will that line be skipped? The purpose of a finally block is that even in exceptional circumastances, the code in the finally block will execute.
There are a lot of other errors which may happen other than opening the file.
In the end you may end up with a fin which is defined or not which you have to protect against null pointer errors, and do not forget that closing the file can throw a new exception.
My advice is to capture this in a separate routine and let the IOExceptions fly out of it :
something like
private String readFile() throws IOException {
String s;
try {
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
s = buffRead.readLine();
fin.close();
} finally {
if (fin != null {
fin.close()
}
}
return s
}
and then where you need it :
try {
loadedString = readFile();
} catch (IOException e) {
// handle issue gracefully
}