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

  • You may not realize the complexity you could be creating when developing mobile apps – many companies don't initially. You could be doubling your IT costs for development and delivery; not to mention, risking sales, productivity and brand satisfaction. Read this IBM-commissioned Forrester Study to understand the key cost drivers of mobile app delivery -- for both customer-facing and enterprise applications. Find out how you could lower costs and increase success with the right strategy and investment.

  • There has been growing buzz about DevOps. DevOps is a methodology that unites the often separate functions of software development (Dev) and production and operations (Ops) into a single, integrated, and continuous process. DevOps is about breaking down the barriers between Dev and Ops. It leverages people, processes, and technology to stimulate collaboration and innovation across the entire software development and release process. Dev and Ops should always be part of an integrated process, but that's not …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date