Creating a Method to Close All Open Objects

The following steps add a closeAll method to the DataHandler class:

  1. Open DataHandler.java in the Java Source Editor by double-clicking it in the Application Navigator.
  2. Declare the closeAll method at the end of the DataHandler class as follows:
    public void closeAll() {
     
    } 
    
  3. Within the method body, check whether the ResultSet object is open as follows:
    if ( rset != null ) {
    
  4. If it is open, close it and handle any exceptions as follows:
      try { rset.close(); } catch ( Exception ex ) {} 
      rset = null;
    } 
    
  5. Repeat the same actions with the Statement object.
    if ( stmt != null ) {
      try { stmt.close(); } catch ( Exception ex ) {} 
      stmt = null;
    }
    
  6. Finally, close the Connection object.
    if ( conn != null ) {
      try { conn.close(); } catch ( Exception ex ) {} 
      conn = null;
    }
    

Example 7-1 Creating a Method to Close All Open Objects

public void closeAll() {
  
  if ( rset != null ) {
    try { rset.close(); 
    } 
    catch ( Exception ex ) {} 
  rset = null;
  }
  
  if ( stmt != null ) {
  try { 
      stmt.close();
  }
  catch ( Exception ex ) {} 
  stmt = null;
  }
  
  if ( conn != null ) {
  try { 
      conn.close(); 
      } 
   catch ( Exception ex ) {} 
conn = null;
  }
 } 

The complete closeAll method should look similar to that shown in Example 7-1.