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: September 10, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild". This loop of continuous delivery and continuous feedback is …

  • This ESG study by Mark Peters evaluated a common industry-standard disk VTl deduplication system (with 15:1 reduction ratio) versus a tape library with LTO-5, drives with full nightly backups, over a five-year period.  The scenarios included replicated systems and offsite tape vaults.  In all circumstances, the TCO for VTL with deduplication ranged from about 2 to 4 times more expensive than the LTO-5 tape library TCO. The paper shares recent ESG research and lots more. 

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds