Constructors

Bruce Eckel's Thinking in Java Contents | Prev | Next

//: Cleanup.java
// Paying attention to exceptions
// in constructors
import java.io.*;
 
class InputFile {
  private BufferedReader in;
  InputFile(String fname) throws Exception {
    try {
      in = 
        new BufferedReader(
          new FileReader(fname));
      // Other code that might throw exceptions
    } catch(FileNotFoundException e) {
      System.out.println(
        "Could not open " + fname);
      // Wasn't open, so don't close it
      throw e;
    } catch(Exception e) {
      // All other exceptions must close it
      try {
        in.close();
      } catch(IOException e2) {
        System.out.println(
          "in.close() unsuccessful");
      }
      throw e;
    } finally {
      // Don't close it here!!!
    }
  }
  String getLine() {
    String s;
    try {
      s = in.readLine();
    } catch(IOException e) {
      System.out.println(
        "readLine() unsuccessful");
      s = "failed";
    }
    return s;
  }
  void cleanup() {
    try {
      in.close();
    } catch(IOException e2) {
      System.out.println(
        "in.close() unsuccessful");
    }
  }
}
 
public class Cleanup {
  public static void main(String[] args) {
    try {
      InputFile in = 
        new InputFile("Cleanup.java");
      String s;
      int i = 1;
      while((s = in.getLine()) != null)
        System.out.println(""+ i++ + ": " + s);
      in.cleanup();
    } catch(Exception e) {
      System.out.println(
        "Caught in main, e.printStackTrace()");
      e.printStackTrace();
    }
  }
} ///:~ 

This example uses Java 1.1 IO classes.

If the FileReader constructor is unsuccessful, it throws a FileNotFoundException, which must be caught separately because that’s the one case in which you don’t want to close the file since it wasn’t successfully opened. Any other catch clauses must close the file because it was opened by the time those catch clauses are entered. (Of course, this is trickier if more than one method can throw a FileNotFoundException. In that case, you might want to break things into several try blocks.) The close( ) method throws an exception that is tried and caught even though it’s within the block of another catch clause – it’s just another pair of curly braces to the Java compiler. After performing local operations, the exception is re-thrown, which is appropriate because this constructor failed, and you wouldn’t want the calling method to assume that the object had been properly created and was valid.

String getLine() throws IOException {
  return in.readLine();
}

But of course, the caller is now responsible for handling any IOException that might arise.

The cleanup( ) method must be called by the user when they are finished using the InputFile object to release the system resources (such as file handles) that are used by the BufferedReader and/or FileReader objects. [46] You don’t want to do this until you’re finished with the InputFile object, at the point you’re going to let it go. You might think of putting such functionality into a finalize( ) method, but as mentioned in Chapter 4 you can’t always be sure that finalize( ) will be called (even if you can be sure that it will be called, you don’t know when). This is one of the downsides to Java – all cleanup other than memory cleanup doesn’t happen automatically, so you must inform the client programmer that they are responsible, and possibly guarantee that cleanup occurs using finalize( ).


[46] In C++, a destructor would handle this for you.



Comments

  • Photo: Chemical test tubes icons illustration vector В© alvaroc #32706306

    Posted by faitildspetle on 12/12/2012 10:58am

    By WebOsPublisher2 Find icons Passage level closed barrier,Icons,images,photos Passage level closed barrier, Icons, IcoMania.com | icons, .ico, images, pictures more than 14 000 icons ! GA_googleFetchAds(); FR | EN | ES Home | Icons | Animals Anime Buildings Cartoons Celebrity Computers Culture Ecology Festivals Flags Folders Foods Furniture Games Guitars Holidays Love Marks Money Movies Music Nature Office Persons Places Recycled bins Religion Science fiction Smiley Space Sports Television Themes Tools Transportations Tv-series Various Video games War Icons Search You are here Home > passage, level, closed, barrier Icons list for passage level closed barrier Icons and images in this page are about : vehicles panels circulation passage level train barrier closed Find more icons circulation, panels, train, vehicles _uacct = "UA-344156-3";urchinTracker(); Icomania.com© 1999 - 2012 iconshoppe.com

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: August 20, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT When you look at natural user interfaces as a developer, it isn't just fun and games. There are some very serious, real-world usage models of how things can help make the world a better place – things like Intel® RealSense™ technology. Check out this upcoming eSeminar and join the panel of experts, both from inside and outside of Intel, as they discuss how natural user interfaces will likely be getting adopted in a wide variety …

  • Savvy enterprises are discovering that the cloud holds the power to transform IT processes and support business objectives. IT departments can use the cloud to redefine the continuum of development and operations—a process that is becoming known as DevOps. Download the Executive Brief DevOps: Why IT Operations Managers Should Care About the Cloud—prepared by Frost & Sullivan and sponsored by IBM—to learn how IBM SmartCloud Application services provide a robust platform that streamlines …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds