File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Exceptions in Finally section Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exceptions in Finally section" Watch "Exceptions in Finally section" New topic
Author

Exceptions in Finally section

satish
Greenhorn

Joined: Jul 03, 2000
Posts: 27
Java tutorial mentions that one of the uses of Finally section is to close any open IO streams. That's what I did in the following code. However, I get "IoTest2.java [30:1] unreported exception java.io.IOException; must be caught or declared to be thrown" error when I compile the code. How should I hadle exceptions thrown in Finally section?

import java.io.*;
public class IoTest2 {

/** Creates a new instance of IoTest2 */
public IoTest2() {
}

public static void main(String[] args){

File f1 = new File("c:\\testfile");
FileReader in = null;
try {
f1.createNewFile();
in = new FileReader(f1);
} catch(IOException e) {
System.out.println(e.getMessage());
} finally {
in.close();
}
}
}


satish
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by satish:
How should I hadle exceptions thrown in Finally section?
The same way you handle them anywhere else: catch them or declare that they will be thrown from the method. Since you print the message of any IOException that occurs while using the file, you may as well do the same when closing it.
satish kumar
Greenhorn

Joined: Nov 26, 2004
Posts: 18
Thank you. If out1.close() fails, system goes to catch block and out2 remains open...right? Should there be another finally?

finally{
try {
out1.close();
out2.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}

}
Pritam Barhate
Greenhorn

Joined: Nov 25, 2004
Posts: 15
no there is no need of another finally. Rather you should use two seperate try{}catch(){} blocks for each of the two close() calls.


Pritam Barhate<br />A magic combination of <b>Code</b> & <b>Fire</b> : <a href="http://www.jroller.org/page/codefire/Weblog" target="_blank" rel="nofollow">codefire</a><br />----------------------------------- <br />My Open Source Projects:<br /><a href="https://acemdi.dev.java.net/" target="_blank" rel="nofollow">AceMDI</a>: A easy, yet powerful MDI framework that manages windows as Tabs.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exceptions in Finally section