Adding Exception Handling to Java Methods

To handle SQL exceptions in the methods in the sample application, do the following:

  1. Ensure that the method throws SQLException. For example, the method:
    public ResultSet getAllEmployees() throws SQLException
    
  2. Use try and catch blocks to catch any SQLExceptions. For example, in the getAllEmployees method, enclose your existing code in a try block, and add a catch block as follows:
    public ResultSet getAllEmployees() throws SQLException {
      try {
        getDBConnection();
        stmt =
          conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
                               ResultSet.CONCUR_READ_ONLY);
        sqlString = "SELECT * FROM Employees order by employee_id";
        System.out.println("\nExecuting: " + sqlString);
        rset = stmt.executeQuery(sqlString);
      } 
      catch (SQLException e) {
        e.printStackTrace();
      }
      return rset;
    }
    
  3. As another example, the deleteEmployee method rewritten to use try and catch blocks would return "success" only if the method was successful, that is, the return statement is enclosed in the try block. The code could be as follows:
      public String deleteEmployeeById(int id) throws SQLException {
     
        try {
          getDBConnection();
          stmt =
            conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
                                 ResultSet.CONCUR_READ_ONLY);
          sqlString = "delete FROM Employees where employee_id = " + id;
          System.out.println("\nExecuting: " + sqlString);
     
          stmt.execute(sqlString);
          return "success";
        }
        catch (SQLException e) {
          e.printStackTrace();
        }
      }