Use Check Or Error

ID

kotlin.use_check_or_error

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Kotlin

Tags

exception, precondition

Description

Reports throw IllegalStateException(…​) expressions. The Kotlin stdlib provides check(condition) { message } for state invariant checks and error(message) for unconditional failure, both with identical runtime semantics and clearer intent.

Rationale

Manual throw IllegalStateException(…​) is verbose and does not communicate whether the site is a recoverable invariant check or an unconditional assertion. The check() and error() functions read as contracts, use lazy message lambdas to avoid string allocation on the happy path, and are idiomatic Kotlin.

// Bad
fun process() {
    if (!initialized) throw IllegalStateException("service not initialized")  // FLAW
    throw IllegalStateException("unreachable branch reached")                 // FLAW
}

// Good
fun process() {
    check(initialized) { "service not initialized" }
    error("unreachable branch reached")
}

Remediation

Replace if (!cond) throw IllegalStateException(msg) with check(cond) { msg }. Replace unconditional throw IllegalStateException(msg) with error(msg).