Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes try-catch-finally ( when and how to close files ??) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "try-catch-finally ( when and how to close files ??)" Watch "try-catch-finally ( when and how to close files ??)" New topic
Author

try-catch-finally ( when and how to close files ??)

david eberhardt
Ranch Hand

Joined: Jul 02, 2002
Posts: 158
hi folks -
been studying from the book "Sun Certified Programmer for Java 2 Study Guide (Exam 310-025)", Second Edition, Copyright 2001 by The McGraw-Hill Companies.
here's some code with accompanying review question found on page 210:

the answer is that the program does not compile due to error on line 13 which is the line where we find "out.close()" in the finally section.
The book says "any method that throws a checked exception must be called within a try clause or the method must declare that it throws the exception.
SO, HOW WOULD YOU HANDLE CODING OF THE "out.close()" call?
a) place the code within a new try-catch block within the finally {}?
b) other ideas?
Note: earlier in the review part for this section, the authors specifically stated "This is the right place to close files, release your network sockets, and perform any other cleanup your code requires". Funny how the test review question seems to disprove that statement!
THANKS
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Originally posted by david eberhardt:

SO, HOW WOULD YOU HANDLE CODING OF THE "out.close()" call?
a) place the code within a new try-catch block within the finally {}?

Correct! like this:
david eberhardt
Ranch Hand

Joined: Jul 02, 2002
Posts: 158
thanks Jessica.
I saw that your response is the same way it is suggested in Pete van der Linden's book "Just Java 2" (Fifth Edition) which is a pretty good book.
I also looked at a program an old work mate wrote which puts the "out.close()" call within the original try block of code. I'm guessing that if you put bothe the open and close within the top try block, you might not be able to tell which line might have casued the IOException, if one occurrs ???
[B] New Question - it looks to me that if I use the method that you mention, I might be able to isolate or identify whether it was a file opening or file closing exception more easily?
[ July 31, 2002: Message edited by: david eberhardt ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try-catch-finally ( when and how to close files ??)
 
Similar Threads
Question on finally
Exception Question
try-catch block ( where to put code to close() files )
Exception
finally