Tuesday, April 27, 2004

Java, JDBC - How to Handle Exceptions and Errors When Closing, or Freeing, Database Resources

When closing database resources it is possible to get multiple exceptions and it is important not to lose any of them. All of the tutorials that I have read only show the use of printStackTrace() during exception handling. However, that approach is not sophisticated enough for Enterprise applications. I use the following technique: Exceptions (and Errors if applicable) are held in an ArrayList until all resources are closed. Then the list is examined. If exceptions are present, they are processed as needed.

    // This code is part of my DataAccess class. Other code in the class is responsible for
    // opening the database connection and creating a prepared statement - both are
    // static objects.

    public synchronized static void free() {
        // This list holds any exception objects that are caught.
        List caughtExceptions = new ArrayList();
        
        if (ps != null) {
            try {
                ps.close();
                logger.debug("free; closed prepared statement.");
            } catch (SQLException e) {
                caughtExceptions.add(e);
            }
        }
        if (con != null) {
            try {
                con.close();
	    	logger.debuf("free; closed database connection.");
            } catch (SQLException e) {
                caughtExceptions.add(e);
            }
        }
        
        if (caughtExceptions.size() > 0) {
            LogConfiguration.message(caughtExceptions, "Problem closing database resources.");
        }
    }

    // Here is the LogConfiguration.message() method which resides in a different class
    // from the above code.

	public static void message(final List exceptions, final String message) {
	    logger.fatal(message);
	    int throwableIndex = 1;
	    int throwableCount = exceptions.size();
	    for (Iterator iter = exceptions.iterator(); iter.hasNext(); ) {
	        Throwable t = (Throwable) iter.next();
		    logger.fatal("Exception [" + throwableIndex + "] of [" + throwableCount + "]", t);
		    throwableIndex++;
	    }
	}

Post a Comment