This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain me.

 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following Program:-


i could'nt understand what is behind in these lines:-

finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which part that you don't understand?

The in.close() closes the InputStream whereas the out.close() closes the OutputStream. Those statements are in the finally clause to ensure that those statements are executed. The checking for the null condition is necessary to avoid the NullPointerException if in or out is null.
 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if (in != null)
and
if(out!=null)
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ashok Pradhan:
if (in != null)
and
if(out!=null)


finally will be executed also if initialization of in and out has failed. Does that give you some clues !!!
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I've already mentioned in my above post, you need to have the null checking in order to prevent your code from having the NullPointerException.


When the code gets into line 4, and suppose that it throws an exception, it will then go to line 11 because of the finally clause, but "in" instance is still null in this case. If you don't do any null checking here, you will get NullPointerException when you try to call in.close(). Similar situation will happen in line 5. Remember, creating an instance of InputStream or OutputStream throws an exception, thus you need to either catch it or throw it.

Hopefully it's clear enough
 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks i got it!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic