• Post Reply Bookmark Topic Watch Topic
  • New Topic

flush() /close()  RSS feed

 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In file writing,
If we omit both the statements flush() & close() ,no Compile or Runtime error but ile is actually not written.
Does this happen?

If i use either of the methods ,file is written.

thnx
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It can happen, yes.

You should always close() a stream when you're done with it. Even if sometimes it seems like it's not necessary - your program will be more reliable if you call close(). (Preferably in a finally block.) Calling close() also calls flush(), so you don't need to call both.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I made a tiny utility to close() anything with a close() method and ignore any exceptions. Have you ever had good reason to catch exceptions on close()?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never encountered a problem on close(). But as I think about it, you could have problems with the flush() that's called as part of the close. Especially if you're dealing with a socket - maybe the connection has been closed since the last time you wrote? If an exception occurs during the flush(), you probably want to treat that the same as an exception during a write(). But any exception during the rest of the close() method is more ignorable. (If it happens at all; I've never seen one.) One thing we don't want is to throw an exception from close() if there was an earlier exception, because that will cause us to lose information about the first exception (which is probably more important).

So I really robust error handling would look something like this:

That's pretty ugly, unfortunately. The outer try/catch can be replaced with a "throws IOException", and the innermost try/catch around the close() can be refactored into a closeSilently() method. Then we have:

Still not as nice as it can be in Ruby or Groovy using closures. Too bad. But for most purposes, this seems to be sufficient:

[ May 01, 2007: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!