Kotlin

Kotlin

Made by DeepSource

Unreachable catch blocks must be removed KT-W1064

Anti-pattern
Major
Autofix

Unreachable catch blocks should be removed, because they serve no useful purpose and can lead to confusing and potentially incorrect behavior in exception handling.

A catch block becomes unreachable when it catches an exception that cannot be thrown within the corresponding try block, or when a former catch block already catches an exception of either the same type or a supertype.

Unreachable catch blocks can become a maintenance burden as developers may not notice extraneous code when making their own changes. It is thus recommended that you remove all unreachable catch blocks from your codebase.

Bad Practice

fun test() {
    try {
        throw Exception()
    } catch (t: Throwable) { // Note: instance of `Throwable` is caught here
        println(t.message)
    } catch (e: Exception) { // Note: instance of `Exception` is caught here
        // Unreachable because `Throwable` is a supertype of `Exception`.
        println(e.message)
    }
}

Recommended

Remove unreachable catch blocks.

fun test() {
    try {
        foo()
    } catch (t: Throwable) {
        println(t.message)
    }
}