Java – Catch incorrect input exceptions

Catch incorrect input exceptions… here is a solution to the problem.

Catch incorrect input exceptions

I have the following two methods

Method one

public String[] getSongIds(String whereClause) 
    {
        String countQuery = "SELECT  songid FROM TABLE_INDEX WHERE " + whereClause;
        Cursor cursor = db.rawQuery(countQuery, null);
        int cursorSize = cursor.getCount();

int[] songIds = new int[cursorSize];
        int count=0;
        if (cursor != null ) {
            if (cursor.moveToFirst()){
                   do{
                       songIds[count] = cursor.getInt(cursor.getColumnIndex("songid"));
                      count++;
                   }while(cursor.moveToNext());
                }
        }
        cursor.close();
        db.close();
        return getSongTitles(songIds);
    }

Method two

private String[] getSongTitles(int[] songIds) {

/some algorithm
    return songTitles;

}

Method 1 is called from a different package. Method 1 Run a query against the SQLite database and call the second method. I need to catch exceptions that are usually caused by executing SQLite queries in Method 1. It’s better to go back (-1) or something so that I can display a message to the user from the package that originally called these methods. So I want method 1 to avoid calling method 2 when there is a (wrong input) SQL exception, and instead return something to another package

p.s I’ve seen several ways to catch this exception but am not happy with their approach. Wondering what is the best way to deal with this. Cheers

Solution

Catch the exception, wrap it in a custom exception and throw it:

public String[] getSongIds(String whereClause) throws FetchSongException {
  String countQuery = "SELECT  songid FROM TABLE_INDEX WHERE " + whereClause;
  try {
    Cursor cursor = db.rawQuery(countQuery, null);
    int cursorSize = cursor.getCount();

int[] songIds = new int[cursorSize];
    int count=0;
    if (cursor != null) {
      if (cursor.moveToFirst()) {
        do {
          songIds[count] = cursor.getInt(cursor.getColumnIndex("songid"));
          count++;
        } while(cursor.moveToNext());
      }
      cursor.close();  you should put this in a finally block
      db.close();
      return getSongTitles(songIds);
    }
  } catch (SQLException sqle) {
    throw new FetchSongException("Unable to fetch song ids.", sqle);
  }
}

Then, the person calling getSongIds needs to catch this new exception:

try {
  String[] result = getSongsIds("something");
} catch (FetchSongException e) {
   Display user message with e.getMessage();
}

Related Problems and Solutions