Ending a transaction can throw an exception in a finally block
We use the following pattern to commit or roll back a transaction:
Transaction txn = db.startTransaction();
try {
db.doSomething(txn);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
DatabaseComponent#endTransaction()
can throw a DbException
, and Android Studio warns about the potential for the exception to be thrown in a finally block.
We should move the exception-throwing code from endTransaction()
into a new commitTransaction()
method, which replaces Transaction#setComplete()
and is called inside the try block. The new contract of endTransaction()
should be to abort the transaction if it has not already been committed, and release the database lock in either case.
Transaction txn = db.startTransaction();
try {
db.doSomething(txn);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
}