Creating a Method for Handling Any SQLException

As a refinement to the code for the sample application, you can create a method that can be used in any method that may throw a SQLException, to handle the exception. As an example, the following method could be called in the catch block of any of the methods in the sample application. This method cycles through all the exceptions that have accumulated, printing a stack trace for each.

In addition, in the catch block, you can return text that explains why the method has failed. The catch block of a method could therefore be written as follows:

catch ( SQLException ex )  {
  logException( ex );
  return "failure";
}

To add this feature to your application:

  1. In the DataHandler.java, add a logException method.
  2. Edit each of the methods to include try and catch blocks.
  3. In the catch block of each method, run the logException method.
  4. For methods that have a return value of String, include a return statement to return a message indicating that the method has failed such as:
    return "failure";
    

Example 5-3 Adding a Method to Handle Any SQLException in the Application

public void logException( SQLException ex )
{
  while ( ex != null ) {
    ex.printStackTrace();
    ex = ex.getNextException();
  }
}