Instanceof Check Exception

ID

kotlin.instanceof_check_exception

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

catch, exception, type-check

Description

Reports is-checks against the caught exception variable inside a catch body. A chain of if (e is X) …​ else if (e is Y) …​ clauses is a strong signal that the surrounding catch is too broad and should be split into multiple catch clauses so the compiler dispatches by type.

Rationale

// Bad — manual type dispatch inside a catch
try { ... } catch (e: Throwable) {
    if (e is IOException) handleIo(e)                                  // FLAW
    else if (e is IllegalStateException) handleState(e)                // FLAW
}

// OK — let the language dispatch
try { ... }
catch (e: IOException) { handleIo(e) }
catch (e: IllegalStateException) { handleState(e) }

Type-based dispatch belongs at the catch level. Doing it manually inside the body duplicates work the compiler already does for free and makes the control flow harder to follow.

Remediation

  • Replace catch (e: BroadType) { if (e is X) …​ else if (e is Y) …​ } with multiple catch clauses, one per concrete exception type.

  • Remove the broad outer catch entirely if it only existed to dispatch by type.