• Post Reply Bookmark Topic Watch Topic
  • New Topic

is null check necessary before closing any io streams ?  RSS feed

 
Musab Qamri
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have initialized streams before try , did some operation in try and need to close the streams in finally block
Do i need to have a null check before closing streams in finally block even if i put them in try... catch?
If yes ... please explain ...

Thanks in advance
 
Manuel Petermann
Ranch Hand
Posts: 177
Hibernate Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you can rule out that the stream is null in the finally block the answer is no you don't have to check.
However I would say you can almost never rule that out.
You should ask yourself what would happen if an exception is thrown at the construction of the stream?
The constructor would throw an exception and the variable would never be assigned to anything.
If you are then trying to call stream.close() you would get a null pointer exception in the finally block.
Having answered your question, what does it have to do with applets specifically?
 
Musab Qamri
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your response ... By mistake it come under applets.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Manuel Petermann wrote:If you can rule out that the stream is null in the finally block the answer is no you don't have to check.
However I would say you can almost never rule that out.

I would say that if you set up your try/finally correctly, you can almost always rule that out. Always, if you control the instantiation yourself (calling the constructor yourself rather than relying on a library).

If any exception is thrown during construction of the stream, we will not enter the try block, and thus will not enter the finally block. If we do enter the try block, we know that the constructor did not throw an exception, and therefore the variable "in" is not null. No null check is necessary.

If you're using Java 7, I recommend try with resources to solve the same problem more concisely.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!