Kotlin

Kotlin

Made by DeepSource

Avoid throwing exceptions within finally blocks KT-W1010

Bug risk
Major

Do not throw exceptions within finally blocks. Doing so can cause exceptions to be lost.

The reason for this is that finally blocks don't share context with the respective try and catch blocks, meaning any exception thrown (and caught) would not directly be visible within the finally block without explicitly saving the exception in a local variable.

Unless there is a very specific reason to do this, and you have taken care to account for any possibly dropped exceptions, avoid doing so.

Bad Practice

fun foo() {
    try {
        // ...
    } finally {
        throw IOException()
    }
}

Recommended

Avoid throwing within finally blocks as much as possible.