3

如果我正在執行一個代碼塊,要求大量變量不爲空,例如在我的Android應用程序中拋出IllegalStateException,在內容提供商delete()功能我:Android和IllegalStateException

public int delete(Uri uri, String where, String[] whereArgs) { 
    try { 
     SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 
     int count; 
     switch (sUriMatcher.match(uri)) { 
      case NOTES: 
       count = db.delete(NOTES_TABLE_NAME, where, whereArgs); 
       break; 

      case NOTE_ID: 
       String noteId = uri.getPathSegments().get(1); 
       count = db.delete(NOTES_TABLE_NAME, NoteColumns._ID + "=" + noteId 
        + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); 
       break; 

      default: 
       throw new IllegalArgumentException("Unknown URI " + uri); 
     } 

     getContext().getContentResolver().notifyChange(uri, null); 
     return count; 

    } catch (NullPointerException e) { 
     // We really shouldn't get any null pointers! 
     throw new IllegalStateException(); 
    } 
} 

因爲,雖然可能性很小,有一個小的機會,下面的變量可能爲NULL:

- mOpenHelper 
- db 
- getContext() 
- getContentResolver() 

或者這是IllegalStateException濫用?我想這樣做的原因是因爲對我來說,這個函數似乎錯了只是拋出NullPointerExceptions

+3

就我個人而言,我更喜歡NPE的全堆棧跟蹤,所以我知道是什麼造成它。如果你想隱藏用戶的實現,但是當某些事情失敗時仍然會回傳,我會主動檢查null或無效的參數,然後用無效的參數拋出異常,並提供其他有用的信息。 –

+0

例如,如果調用者是一個活動:你會嘗試{getContentResolver()。delete(myUri,myWhere,myWhereArgs); } catch(NullPointerException e){//使用e做東西}? – Mewzer

+1

'db',''getContext()'和'getContentResolver()'不能返回null,'mOpenHelper'這是對你自己類的引用,如果你正確的話我不會看到它是'null'在提供者中實例化它。 – Luksprog

回答

1

至少應使用throw new IllegalStateException(e);來保留首先引發異常的信息。

我會親自確認NPE不能通過確保所有必需的變量(mOpenHelper等)在我需要使用它們之前正確初始化而發生。

+0

我同意 - 我試圖確保NPE不會發生。不過,我想添加一個明確的檢查,以防萬一(因爲你永遠不會說永遠!)。 – Mewzer

+1

@Mewzer我認爲下一個問題確實是:如果你得到NPE,你能不能恢復?如果可以的話,抓住它並且恢復,如果你不能讓它冒出來並且在最高級別捕捉它,以便給出「意外的錯誤blabla」。 – assylias

+0

謝謝 - 在這種情況下,如果任何一個碰巧是空的,那麼我想這是不可能恢復的。 – Mewzer

1

爲什麼不創建自己的異常?

public class MyCustomException extends NullPointerException { 

    private static final long serialVersionUID = 1L; 

    public Exception innerException; 

    public MyCustomException() {} 

    public MyCustomException(Exception innerException) { 
     this.innerException = innerException; 
    } 
} 

... 

if (mOpenHelper == null){thrown new MyCustomException("mOpenHelper is null!");} 

或者,趕上NPE,找出原因,然後拋出自己的。

相關問題