Do i need to handle or ignore the IOException fired by OutputStream close() function?
Asked Answered
K

4

5

In the following code the close function for outPutStream throw an IOException exception that I should catch. My question is do I need to handle it? Since I'm working with mobile devices and I want to make sure that I free all resources that I use, or could I safely ignore the exception.

//...
OutputStream output = null;
try {
     output = connection.getOutputStream();
     output.write(query.getBytes(charset));
} finally {
     if (output != null) try { 
        output.close(); 
     } catch (IOException e) {
        // Do i need to do something here ?
     }
}
Kosygin answered 14/12, 2011 at 15:47 Comment(4)
You should never ignore exceptions that could be thrown, have a look at the Try-With resources block new in Java 7, it will may this code look a little prettier: docs.oracle.com/javase/tutorial/essential/exceptions/…Zendah
What can you do with it?Summerville
Yeah, that one has always made me scratch my head. What I always do is just log the error, so that if it ever happens I know it did—but I have no clue what one would have to do to recover in this situation (if anything).Imide
Hunter McMillen: but the try-with-resources block you're recommending can have the effect of ignoring the exception that Jimmy's asking how to handle. Read your link's discussion of "suppressed" exceptions.Imide
P
7

If the close doesn't work, what can you do?

The only thing you can do is just log the exception, and as @mprabhat has suggested you can set the reference to null to speed up GC.

Pantia answered 14/12, 2011 at 15:50 Comment(5)
Does it make sense to call flush() ? or it cant be performed.Kosygin
I think that would throw IOException as wellPantia
I think it dosent make sense, after a little reading close will call flush first.Kosygin
In my comment above, I am assuming that we are in the condition that your close() has already thrown an exception.Pantia
Sorry, im not referring to your comment. i was talking about my first assumption. Thanks for follow up.Kosygin
C
3

The java documentation doesn't detail on which all different condition close will throw an IOException hence there isn't much that one can do.

At least you can set the reference of OutputStream to null and log the exception.

Carhop answered 14/12, 2011 at 15:52 Comment(0)
R
0

In worst case, you can give a warning. But generally, such exceptions are thrown when trying to close an already closed session. In this case, you don't need to do anything.

Rycca answered 14/12, 2011 at 15:51 Comment(0)
I
0

In Effective Java Joshua Bloch mentions this as one of the exceptions you might want to ignore. Generally though, he says, you do want to do more with exceptions than just logging them.

Insectarium answered 3/6, 2017 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.