# Use with finally

**URL:** <https://discuss.kotlinlang.org/t/use-with-finally/4848>\
**Category:** Language Design\
**Created:** [October 3, 2017, 8:49pm UTC](https://discuss.kotlinlang.org/t/use-with-finally/4848 "2017-10-03T20:49:42Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![benjishults](https://avatars.discourse-cdn.com/v4/letter/b/c0e974/32.png) [@benjishults](https://discuss.kotlinlang.org/u/benjishults)\
**Post date:** [October 3, 2017, 8:49pm UTC](https://discuss.kotlinlang.org/t/use-with-finally/4848/1 "2017-10-03T20:49:42Z")

</div>

The following would be nice:

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.

---

<div class="post-metadata">

**Author:** ![ahmadalsharif.dev](https://avatars.discourse-cdn.com/v4/letter/a/bbe5ce/32.png) [@ahmadalsharif.dev](https://discuss.kotlinlang.org/u/ahmadalsharif.dev)\
**Post date:** [October 4, 2017, 4:23am UTC](https://discuss.kotlinlang.org/t/use-with-finally/4848/2 "2017-10-04T04:23:21Z")

</div>

Use is meant to omit finally and catch. If you need finally and catch well use it the classic way with a try block instead

---

<div class="post-metadata">

**Author:** ![Stephan\_Knull](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/stephan_knull/32/11318_2.png) [@Stephan\_Knull](https://discuss.kotlinlang.org/u/Stephan_Knull)\
**Post date:** [October 26, 2025, 8:26am UTC](https://discuss.kotlinlang.org/t/use-with-finally/4848/3 "2025-10-26T08:26:08Z")

</div>

I just stumble across this as I have a similar need.

Maybe something similar as with runCatching blocks would be hellpful:  
having optional .onSuccess and .onFailure blocks.

This would fit into the language syntax and helps in special cases.

---

<div class="post-metadata">

**Author:** ![Landei](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/landei/32/9407_2.png) [@Landei](https://discuss.kotlinlang.org/u/Landei)\
**Post date:** [October 26, 2025, 10:51am UTC](https://discuss.kotlinlang.org/t/use-with-finally/4848/4 "2025-10-26T10:51:37Z")

</div>

Behold, the power of DSLs:

```kotlin
fun <T : Closeable?, R : Any> T.useCatching(
    block: (T) -> R
): UseCatching<T, R> = UseCatching(this, block)

data class UseCatching<T : Closeable?, R : Any>(
    val t: T,
    val block: (T) -> R,
    val catchBlocks: List<CatchBlock<*, T, R>> = emptyList()
) {
    inline infix fun <reified E : Exception> CATCH(noinline catchBlock: T.(E) -> R) =
        UseCatching(t, block, catchBlocks + CatchBlock(E::class, t, catchBlock))

    infix fun FINALLY(finallyBlock: T.() -> Unit): R =
        try {
            t.use(block)
        } catch (e: Exception) {
            catchBlocks.firstNotNullOfOrNull { it.runIfPossible(e) } ?: throw e
        } finally {
            t.finallyBlock()
        }
}

data class CatchBlock<E : Exception, T : Closeable?, R : Any>(
    val exceptionClass: KClass<E>,
    val t: T,
    val block: T.(E) -> R
) {
    fun runIfPossible(e: Exception): R? {
        return if (exceptionClass.isInstance(e)) {
            with(t) {
                @Suppress("UNCHECKED_CAST") block(e as E)
            }
        } else null
    }
}

```

Usage:

```auto
val i = connection.useCatching {
    if (3 == 4) throw ArithmeticException()
    throw NullPointerException()
    23
} CATCH { a: ArithmeticException ->
    println("AE $a"); 42
} CATCH { n: NullPointerException ->
    println("NPE $n"); 0
} FINALLY { println("Finally!") }

```

Disclaimer: No guarantees, this is just a proof of concept

---

<div class="post-metadata">

**Author:** ![kyay10](https://avatars.discourse-cdn.com/v4/letter/k/c57346/32.png) [@kyay10](https://discuss.kotlinlang.org/u/kyay10)\
**Post date:** [October 26, 2025, 11:11am UTC](https://discuss.kotlinlang.org/t/use-with-finally/4848/5 "2025-10-26T11:11:21Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Skater901](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/skater901/32/10163_2.png) [@Skater901](https://discuss.kotlinlang.org/u/Skater901)\
**Post date:** [October 26, 2025, 11:58am UTC](https://discuss.kotlinlang.org/t/use-with-finally/4848/6 "2025-10-26T11:58:21Z")

</div>

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:

```kotlin
fun <T, R> T.useDatabase(block: T.() -> R): R where T : DatabaseConnection, DatabaseTransaction = try {
    block()
} finally {
    rollBackTransaction()
    closeConnection()
}

```
