捕获错误的输入异常

5cnsuln7  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(373)

我有以下两种方法
方法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、 我看到了几种方法来捕捉这个异常,但对它们的方法并不满意。想知道处理这件事的最佳方法是什么。干杯

k5ifujac

k5ifujac1#

捕获异常,将其 Package 为自定义异常,然后抛出它:

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

相关问题