aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Groovy Fundamentals video training course this week in the Groovy forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception Question" Watch "Exception Question" New topic

Exception Question

Ranch Hand

Joined: Dec 16, 2005
Posts: 103
Hello Guru�s,

I couldn�t understand the following question and answer. Because the catch handles IOException and the finally closing the open file based on the definition below and finally not throw any exception. Then why this got compilation error.

Thanks, Raghu.K

Definition :-

A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement! This is the right place to close your files, release your network sockets, and perform any other cleanup your code requires. If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. If there was an exception thrown, the finally block executes immediately after the proper catch block completes.

1. import*;
2. public class MyProgram {
3. public static void main(String args[]){
4. FileOutputStream out = null;
5. try {
6. out = new FileOutputStream("test.txt");
7. out.write(122);
8. }
9. catch(IOException io) {
10. System.out.println("IO Error.");
11. }
12. finally {
13. out.close();
14. }
15. }
16. }

and given that all methods of class FileOutputStream, including close(), throw an IOException, which of these is true? (Choose one.)
A. This program will compile successfully.
B. This program fails to compile due to an error at line 4.
C. This program fails to compile due to an error at line 6.
D. This program fails to compile due to an error at line 9.
E. This program fails to compile due to an error at line 13.

Answer Is :- E.
J Sato
Ranch Hand

Joined: Mar 30, 2006
Posts: 40
Because the out.close() method can throw an IOException, it must be handled or declared. This modified example will compile successfully:

Remember that code within the finally block can throw an Exception. The finally block will run regardless of what happens in the try/catch (with the exception of System.exit()) but is not guaranteed to complete.

[ April 13, 2006: Message edited by: J Sato ]
I agree. Here's the link:
subject: Exception Question