File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions in Finally section

 
satish
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
}
}
 
David Harkness
Ranch Hand
Posts: 1646
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no there is no need of another finally. Rather you should use two seperate try{}catch(){} blocks for each of the two close() calls.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic