Search code examples
javaandroiddatabasesqlitecreate-table

Rethrow Exception in Android SQLite Database onCreate()


Hey this is my onCreate method for a SQLiteDatabase that is of course called when a new database is created. I want to catch any problem and log and then rethrow it for handling up above. However the compiler is not allowing me to rethrow the exception, complaining that it is not handled. This is on the line that reads "throw e;".

@Override
public void onCreate(SQLiteDatabase db) {//arg0?
    db.beginTransaction();
    try {
        Checklist.createTable(db);
        Item.createTable(db);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(KnowUrStuffApp.TAG,"KusDBHelper.onCreate: " + e.getLocalizedMessage());           
        db.endTransaction();
        throw e;//SYNTAX ERROR: Unhandled Exception Type Exception
    }
}

Solution

  • Your problem is, that you're throwing a checked exception. This can only be done when this exception is

    1. directly caught and handled by a try/catch-block
    2. or the exception is thrown "upwards" by adding throws SomeException to your method-signature.

    However, in your case, you're overriding the onCreate()-method, which (in the base-class) does not throw a checked exception. Therefore, you can't override the method and add throws to the signature, because that wouldn't be an override anymore.

    What you can do is, throw a RuntimeException upwards, which doesn't need to be added to the method signature:

    Log.e(KnowUrStuffApp.TAG,"KusDBHelper.onCreate: " + e.getLocalizedMessage());           
    db.endTransaction();
    throw new RuntimeException(e); // Add the checked exception as the cause!
    

    For more information on Exceptions (throwing and catching), see my blog-post: Catching practice