Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 390
Umbungu Avatar asked Dec 11 '25 07:12

Umbungu


2 Answers

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.

like image 132
assylias Avatar answered Dec 12 '25 21:12

assylias


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.

like image 37
Simon Avatar answered Dec 12 '25 22:12

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!