Does close()ing InputStream release resoures even if it throws? - java

Just a simple question. Given this code:
try {
// operation on inputstream "is"
} finally {
try {
is.close();
} catch (IOException ioe) {
//if ioe is thrown, will the handle opened by 'is' be closed?
}
}
If the close() throws, is the file handle still around (and leaked), or will it have been closed?

Not reliably so. If is.close() throws, is might not be marked closed. In any case, there is nothing you can do about it. You don't know the internals of is. The Java 7 equivalent simply hides the problem.
try (InputStream is = Files.newInputStream(...)) {
// Stuff with is.
} catch (IOException is) {
... // Handles exceptions from the try block.
} // No finally. Handled by try-with-reources
If the auto-close throws, the exception is a suppressed exception, and you'll never know if or when the file handle is reclaimed.

Related

try-with-resource vs ordinary code with explicit close()-call [duplicate]

This question already has answers here:
What's the purpose of try-with-resources statements?
(7 answers)
Closed 2 years ago.
I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs Try-Catch what are the differences between those, and which is better.
Here is a try with resources :
objects jar = new objects("brand");
objects can= new objects("brand");
try (FileOutputStream outStream = new FileOutputStream("people.bin")){
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
}
The main point of try-with-resources is to make sure resources are closed reliably without possibly losing information.
When you don't use try-with-resources there's a potential pitfall called exception-masking. When code in a try block throws an exception, and the close method in the finally also throws an exception, the exception thrown by the try block gets lost and the exception thrown in the finally gets propagated. This is usually unfortunate, since the exception thrown on close is something unhelpful while the informative one is the one thrown from within the try block. (So instead of seeing the SQLException that tells you which referential integrity constraint was violated, you're shown something like BrokenPipeException where closing the resource failed.)
This exception-masking is an annoying problem that try-with-resources prevents from happening.
As part of making sure exception-masking wouldn't lose important exception information, when try-with-resources was developed they had to decide what to do with the exceptions thrown from the close method.
With try-with-resources, if the try block throws an exception and the close method also throws an exception, then the exception from the close block gets tacked on to the original exception:
... there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
On the other hand if your code completes normally but the resource you're using throws an exception on close, that exception (which would get suppressed if the code in the try block threw anything) gets thrown. That means that if you have some JDBC code where a ResultSet or PreparedStatement is closed by try-with-resources, an exception resulting from some infrastructure glitch when a JDBC object gets closed can be thrown and can rollback an operation that otherwise would have completed successfully.
Without try-with-resources whether the close method exception gets thrown is up to the application code. If it gets thrown in a finally block when the try block throws an exception, the exception from the finally block will mask the other exception. But the developer has the option of catching the exception thrown on close and not propagating it.
You missed something, the finally block. The try-with-resouces will make it something like,
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
}
}
}
Which means you really wanted something like (never swallow exceptions),
try (FileOutputStream outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);) {
stream.writeObject(jar);
stream.writeObject(can);
// stream.close(); // <-- closed by try-with-resources.
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
} catch(IOException f) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
}
The only difference is that try-resource is adding automatically resource.close();
as you would do in finally block
Any object (either the class or their superclass) that implements java.lang.AutoCloseable or java.io.Closeable
can only be used in try-with-resource clause.
AutoClosable interface is the parent interface and Closable interface extends the AutoClosable interface.AutoClosable interface has method close which throws Exception while Closable interface has method that throws IOException.
We can also have catch and finally block followed by try-with-resource like ordinary try, catch and finally, but catch and finally block only get executed once the resource declared inside the try-with-resource clause is closed.
Succinctly it is syntactic sugar to support the AutoClosable interface and call the close() method for you for any outcome.

what's try method means in java? [duplicate]

This question already has answers here:
What's the purpose of try-with-resources statements?
(7 answers)
Closed 2 years ago.
I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs Try-Catch what are the differences between those, and which is better.
Here is a try with resources :
objects jar = new objects("brand");
objects can= new objects("brand");
try (FileOutputStream outStream = new FileOutputStream("people.bin")){
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
}
The main point of try-with-resources is to make sure resources are closed reliably without possibly losing information.
When you don't use try-with-resources there's a potential pitfall called exception-masking. When code in a try block throws an exception, and the close method in the finally also throws an exception, the exception thrown by the try block gets lost and the exception thrown in the finally gets propagated. This is usually unfortunate, since the exception thrown on close is something unhelpful while the informative one is the one thrown from within the try block. (So instead of seeing the SQLException that tells you which referential integrity constraint was violated, you're shown something like BrokenPipeException where closing the resource failed.)
This exception-masking is an annoying problem that try-with-resources prevents from happening.
As part of making sure exception-masking wouldn't lose important exception information, when try-with-resources was developed they had to decide what to do with the exceptions thrown from the close method.
With try-with-resources, if the try block throws an exception and the close method also throws an exception, then the exception from the close block gets tacked on to the original exception:
... there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
On the other hand if your code completes normally but the resource you're using throws an exception on close, that exception (which would get suppressed if the code in the try block threw anything) gets thrown. That means that if you have some JDBC code where a ResultSet or PreparedStatement is closed by try-with-resources, an exception resulting from some infrastructure glitch when a JDBC object gets closed can be thrown and can rollback an operation that otherwise would have completed successfully.
Without try-with-resources whether the close method exception gets thrown is up to the application code. If it gets thrown in a finally block when the try block throws an exception, the exception from the finally block will mask the other exception. But the developer has the option of catching the exception thrown on close and not propagating it.
You missed something, the finally block. The try-with-resouces will make it something like,
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
}
}
}
Which means you really wanted something like (never swallow exceptions),
try (FileOutputStream outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);) {
stream.writeObject(jar);
stream.writeObject(can);
// stream.close(); // <-- closed by try-with-resources.
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
} catch(IOException f) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
}
The only difference is that try-resource is adding automatically resource.close();
as you would do in finally block
Any object (either the class or their superclass) that implements java.lang.AutoCloseable or java.io.Closeable
can only be used in try-with-resource clause.
AutoClosable interface is the parent interface and Closable interface extends the AutoClosable interface.AutoClosable interface has method close which throws Exception while Closable interface has method that throws IOException.
We can also have catch and finally block followed by try-with-resource like ordinary try, catch and finally, but catch and finally block only get executed once the resource declared inside the try-with-resource clause is closed.
Succinctly it is syntactic sugar to support the AutoClosable interface and call the close() method for you for any outcome.

Should we ignore IOException while close Buffered stream?

I load a xml content, and save it to the disk. Then I read it, and try to parse.
When I have successfully parsed xml, should I ignore IOException in 7 line?
catch (IOException ignore) {}
Or some problems may occured?
private HashMap <String, VideoDto> loadContent(String url){
try {
BufferedInputStream bStream = httpGateway.loadContents();
cachedContent = xmlParser.parseVideos(bStream);
try {
bStream.close();
} catch (IOException ignore) {}
return cachedContent;
} catch (XMLStreamException e) {
throw new IllegalStateException("I/O error during integration", e);
}
}
public BufferedInputStream loadContents() {
URL source = config.getContentPath();
URL target= config.getLastImportedFile();
try {
ReadableByteChannel rbc = Channels.newChannel(source.openStream());
FileOutputStream fos = new FileOutputStream(target.getFile());
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Wrong url format", e);
} catch (IOException e) {
throw new IllegalArgumentException("I/O error while saving "+target, e);
}
return createBufferStream(config.getLastImportedFile());
}
private BufferedInputStream createBufferStream(URL url){
try {
return new BufferedInputStream(url.openConnection().getInputStream());
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
There are three parts to this question:
Q1: Should one ever ignore (squash) an exception?
I think that the answer is ... "it depends".
If the exception cause is known AND it you can catch it precisely (i.e. without also catching exceptions with different causes) AND the correct thing to do is to ignore it then ... IMO ... Yes it is acceptable.
Otherwise. No.
Q2: What does and IOException mean in this case, and does it matter?
The answer is that it is not at all clear. Under normal circumstances, one would not expect an IOException when closing an input stream, and it is hard to know what it might mean. Intuitively it is probably harmless. On the other hand, if you don't know what might cause something it is hard to say whether or not it matters.
Q3: Should you simply ignore this IOException?
I would say no. But I would handle it like this:
} catch (IOException ex) {
// possibly log the exception here.
throw new AssertionError("Unexpected exception", ex);
}
The rationale is that if something totally unexpected does occur, then it would be a good thing if the developer / maintainer could find out, and figure out how to deal with it.
On the other hand, if you could make an a priori assessment that any IOException here is harmless, then simply logging (or even squashing) it might be sufficient.
Never ignore exceptions, even if nothing goes wrong. This is the seed of bugs.
The desired thing to do, if you don't need any actions to be done, is, print its stack trace.
e.printStackTrace();
You may ignore that at any time, but may help you in the long run.
Use the try syntax that exists since Java 7:
try (BufferedInputStream bStream = httpGateway.loadContents();) {
cachedContent = xmlParser.parseVideos(bStream);
}
With this you don't have to call .close() manually.
You should catch all exceptions that are thrown inside the try block, though.
This means that the stream will (probably) still be open, whether that is a problem in your program only you will know. At the very least you should log the exception, otherwise you might get strange results that are hard to detect.
You might also want to look at the try-with-resources syntax which doesn't pose this dilemma:
try (BufferedInputStream bStream = httpGateway.loadContents()) {
cachedContent = xmlParser.parseVideos(bStream);
}
In Effective Java Joshua Bloch gives this as an example of an exception you might want to log and ignore. He says, however, that in general you want to do more than just logging an exception.

Does finally completely execute if an exception is thrown within finally block

so I have a bit of code here and I'm not sure entirely how it would react in the event that the reader.close() method throws an exception.
public void someMethod(String s) throws IOException{
BufferedReader reader = Files.newBufferedReader(filePath,cs);
listRWLock.readLock().lock();
try{
//miscellaneous code involving reading
}finally{
reader.close()
listRWLock.readLock().unlock()
}
}
ListRWLock is a ReentrantReadWriteLock. In the event that the reader.close() method throws an exception, would the statement after it fail to execute? I've tried searching for the topic, and while I've gotten something about finally executing in the event of return statements, I haven't managed to find details on what happens if an exception is thrown within the finally block.
Thanks in advance.
Basically, finally clauses are there to ensure proper release of a resource. However, if an exception is thrown inside the finally block, that guarantee goes away.
An issue for which there's no really neat solution is that code in the finally block could itself throw an exception. In this case, the exception in the finally block would be thrown from the exception instead of any exception occurring inside the try block. Since code in the finally block is intended to be "cleanup" code, we could decide to treat exceptions occurring there as secondary, and to put an excplicit catch:
public int readNumber(File f) throws IOException, NumberFormatException {
BufferedReader br = new BufferedReader(new
InputStreamReader(new FileInputStream(f), "ASCII"));
try {
return Integer.parseInt(br.readLine());
} finally {
try { br.close(); } catch (IOException e) {
// possibly log e
}
}
}
Some other things to note about finally blocks:
The same 'overriding' problem that we mentioned with exceptions
occurs when returning a value from a finally block: this would
override any return value that the code in the try block wanted to
return. In practice, returning a value from a finally clause is rare
and not recommended.
Actually exiting the program (either by calling System.exit() or by
causing a fatal error that causes the process to abort: sometimes
referred to informally as a "hotspot" or "Dr Watson" in Windows)
will prevent your finally block from being executed!
There's nothing to stop us nesting try/catch/finally blocks (for
example, putting a try/finally block inside a try/catch block, or
vice versa), and it's not such an uncommon thing to do.
You can do something like this:
try{
//miscellaneous code involving reading
}finally{
handlePossibleException(reader);
listRWLock.readLock().unlock()
}
handlePossibleException(BufferedReader reader) {
try {
if (reader != null) {
reader.close();
}
} catch( Exception e ) {
log.e( "reader.close() Exception: ", e );
}
}
You should test this,
but if try throws IO Exception, then your reader wont close.
Maybe have
catch(IOException ex){
reader.close()
An exception can happen anywhere in your code, including finally block, so you have to catch it as anywhere else in your code. Check the following post to get some ideas about the ways you can handle such situation:
throws Exception in finally blocks

What is the correct way to silently close InputStream in finally block without losing the original exception?

I am wondering if the below code closes InputStream in finally block correctly
InputStream is = new FileInputStream("test");
try {
for(;;) {
int b = is.read();
...
}
} finally {
try {
is.close();
} catch(IOException e) {
}
}
If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?
Best way is to use Java 7 and use try with resources, or do same thing manualy and add exception from closing as suppressed exception.
Pre Java 7:
If you are throwing your custom exception, you can add in it supressed exception like it is done in Java 7 (in your exception create fields List suppressed and put there exceptions from close operation and when dealing with your exception, look there too.
If you cannot do that, I don't know anything better than just log it.
examples:
from Java tutorials
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
but better form is:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
This way even if creation of FileReader is succesfull but creation of BufferedReader fails (eg not enough memory), FileReader will be closed.
You can close it with IOUtils from https://commons.apache.org/proper/commons-io/
public void readStream(InputStream ins) {
try {
//do some operation with stream
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(ins);
}
}
The Java 6 specs say
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So you are right, you will lose the original exception.
The solution probably is to write your finally block so defensively that it is a bigger surprise (worth propagating) if the finally block fails than if an exception comes out of the try catch block.
So, for example, if it is possible that the stream may be null when you try to close it, check it:
InputStream is = new FileInputStream("test");
try {
for(;;) {
int b = is.read();
...
}
} finally {
try {
if( is!=null ) {
is.close();
}
} catch(IOException e) {
}
}
In Java 7, Alpedar's solution is the way to go of course.
The exception from is.close() will be suppressed and the exception from is.read() will be the one that propagates up.
With the code you posted:
If is.close() throws an IOException, it gets discarded and the original exception propagates.
If is.close() throws something else (a RuntimeException or an Error), it propagates and the original exception is discarded.
With Java 7, the correct way to close an InputStream without loosing the original exception is to use a try-with-resources statement:
try (InputStream is = new FileInputStream("test")) {
for(;;) {
int b = is.read();
// ...
}
}
Prior to Java 7, what you do is just fine, except you may want to catch all exceptions instead of just IOExceptions.
Based on your code sample if an exception occurs at the int b = is.read(); point, then the exception will be raised higher up the call chain.
Note though that the finally block will still execute and if the Inputstream invalid another exception will be thrown, but this exception will be "swallowed", which may be acceptable depending on your use case.
Edit:
Based on the title of your question, I would add that what you have is fine in my opinion. You may want to additionally add a catch block to explicitly handle (or perhaps wrap) any exception within the first try block, but it is also acceptable to let any IO exceptions raise up - this really depends on your API. It may or may not be acceptable to let IO exceptions raise up. If it is, then what you have it fine - if it isn't then you may want to handle/wrap the IO exception with something more suitable to your program.
How about the next solution:
InputStream is = new FileInputStream("test");
Exception foundException=null;
try {
for(;;) {
int b = is.read();
...
}
} catch (Exception e){
foundException=e;
}
finally {
if(is!=null)
try {
is.close();
} catch(IOException e) {
}
}
//handle foundException here if needed
If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?
Yes. You have a catch block for the exception in close() which does not re-throw the exception. Ergo it is not propagated or rethrown.
This is the sample to help to understand your problem,
if you declare the scanner in the try-catch block it will give compiler warning the resource is not closed.
so either make it locally or just in try()
import java.util.InputMismatchException;
import java.util.Scanner;
class ScanInt {
public static void main(String[] args) {
System.out.println("Type an integer in the console: ");
try (Scanner consoleScanner = new Scanner(System.in);) {
System.out.println("You typed the integer value: "
+ consoleScanner.nextInt());
} catch (InputMismatchException | ArrayIndexOutOfBoundsException exception) {
System.out.println("Catch Bowled");
exception.printStackTrace();
}
System.out.println("----------------");
}
}

Categories

Resources