I created an I/O stream say FileInputStream, when i am over using it i call its close() method. But my IDE shows error and suggest it to be wrapped inside a try-catch block.
Now if exception occurs in closing the stream how will it finally get closed? Even i put the close() statement in 'finally block', it suggests to enclose in try-catch block.
Thats really confusing.
Not really. It's the only way to separate IOExceptions thrown by the close() method from IOExceptions thrown by "actual" code. Still, I prefer the shorter version that does not make the distinction. It looks like Andrey's code but doesn't need the null check:
But the Java 7 way, with try-with-resources, is even better:
The first line is new syntax, and it will make sure fis is automatically closed when the try block ends.
I hate the ugly code that results from having try-catch in a finally clause so I have an IO utility class that contains a forceClose() method -
I just call this in the finally clause.
Note - one doesn't actually need the 'null' check since a NullPoinerException will be thrown and caught but ...
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Joined: Jul 11, 2010
I guess i am not clear about this...
Firstly, what are the reason for i/o stream to throw exception?
Secondly, why wouldn't it throw if it is inside try or finally or anywhere? If we can have a try inside another try's finally clause...then it should be try inside try inside try and so on!
Ashish Malik wrote:Firstly, what are the reason for i/o stream to throw exception?
While doing I/O all kinds of things could happen. For instance (and this actually happened to me once) your Ethernet cable could be disconnected. Then communication isn't possible any more. How else would the jvm communicate this problem?
Ashish Malik wrote:Secondly, why wouldn't it throw if it is inside try or finally or anywhere? If we can have a try inside another try's finally clause...then it should be try inside try inside try and so on!
If you have multiple resources then yes you'll need to nest a lot of try-catch-finally statements. That's why they invented try-with-resources in Java 7.