Umbungu
Umbungu

Reputation: 975

Android and IllegalStateException

Would it be valid for me to throw an IllegalStateException in my Android application if I am executing a chunk of code that requires a number of variables not to be null, e.g. in the content provider delete() function I have:

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

Because, although highly unlikely, there is a small chance that the following variables could be NULL:

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

Or is this an abuse of IllegalStateException? The reason I want to do this is because to me it seems wrong for this function to just throw NullPointerExceptions?

Upvotes: 3

Views: 443

Answers (2)

assylias
assylias

Reputation: 328745

At the minimum, use throw new IllegalStateException(e); to keep the information about what caused the exception in the first place.

I would personally make sure that NPE cannot happen by making sure that all the required variables (mOpenHelper etc) are properly initialised before I need to use them.

Upvotes: 1

Simon
Simon

Reputation: 14472

Why not create your own exception?

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

Or, just catch the NPE, figure out why, then throw up your own.

Upvotes: 1

Related Questions