File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Exceptions in Finally section


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 " [30:1] unreported exception; must be caught or declared to be thrown" error when I compile the code. How should I hadle exceptions thrown in Finally section?

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 {
in = new FileReader(f1);
} catch(IOException e) {
} finally {

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

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?

try {
} catch (IOException e) {

Pritam Barhate

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="" target="_blank" rel="nofollow">codefire</a><br />----------------------------------- <br />My Open Source Projects:<br /><a href="" target="_blank" rel="nofollow">AceMDI</a>: A easy, yet powerful MDI framework that manages windows as Tabs.
I agree. Here's the link:
subject: Exceptions in Finally section
It's not a secret anymore!