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: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds