繁体   English   中英

捕获错误的输入异常

[英]Catching wrong input 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)或者其他什么,这样我就可以从最初调用这些方法的包中向用户显示一条消息。 因此,如果存在(错误的输入)SQL异常,我希望方法1避免调用方法2,而是将某些东西返回给另一个包

ps我看到几种方法来捕捉这个异常,但对他们的方法并不满意。 想知道什么是解决这个问题的最佳方法。 干杯

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM