捕获错误的输入异常

时间:2012-08-25 01:59:42

标签: java android exception

我有以下两种方法

方法1

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);
    }

方法2

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

    /some algorithm
    return songTitles;

}

从不同的包中调用方法1。方法1对SQLite数据库运行查询并调用第二个方法。我需要经常通过在方法1中执行SQLite查询来捕获异常。最好返回(-1)或者其他什么,这样我就可以从最初调用这些方法的包中向用户显示一条消息。所以我希望方法1避免在有(错误的输入)SQL异常的情况下调用方法2,而是将某些东西返回给另一个包

p.s我看到了几种方法来捕捉这个异常,但对他们的方法并不满意。想知道什么是解决这个问题的最佳方法。欢呼声

1 个答案:

答案 0 :(得分:3)

捕获异常,将其包装在自定义异常中,并将其抛出:

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);
  }
}

然后,无论谁调用getSongIds都需要捕获这个新的异常:

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