• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Exceptions in Finally section

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
}
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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());
}

}
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Now I am super curious what sports would be like if we allowed drugs and tiny ads.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic