connection.use {
// …
} catch (e: UniquenessConstraintException) {
// fix it
} finally {
// other stuff
}
I know “use” is currently a function and finally and catch are (soft) keywords. Also, I’m aware that I can wrap use in a try block so this is probably not worth the trouble. Just throwing the idea out there to see what you folks think.
I’m a little wary of this since if one forgets a FINALLY, the entire thing just doesn’t run. It’s also not inline, but I don’t think there’s a way to make it so.
I think the question that really needs to be asked is “Why do you need this?” Imo, the point of a finally block is to do any clean up that needs to be done regardless of whether an exception occurs. Usually that’s things like closing connections. Well, with Closeable and AutoCloseable and the use function in Kotlin, all of that stuff is taken care of for us, so what would need to go in the finally block that couldn’t just go after the try / catch? If you have some kind of custom closing logic, perhaps you could create your own custom use function that works on a generic union type or something.
For example:
fun <T, R> T.useDatabase(block: T.() -> R): R where T : DatabaseConnection, DatabaseTransaction = try {
block()
} finally {
rollBackTransaction()
closeConnection()
}