No Throw Throwable
ID |
kotlin.no_throw_throwable |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Kotlin |
Tags |
CWE:397, exception, throw |
Description
Reports throw Throwable(…), throw Exception(…) and throw RuntimeException(…)
expressions. These umbrella exception types give callers no information about what actually
went wrong and force catch sites to either over-catch or to inspect message strings.
Rationale
// Bad — no information about the failure mode
throw Throwable("something went wrong") // FLAW
throw Exception("invalid state") // FLAW
throw RuntimeException("bad input") // FLAW
// OK — specific type carries intent
throw IllegalStateException("cache not initialised")
throw IllegalArgumentException("amount must be positive")
throw IOException("failed to read $path", cause)
Catch sites can react meaningfully only when they can name the exception they care about. Generic throws push that decision back onto string parsing, which is brittle and rarely exhaustive.
Remediation
-
Throw a specific subclass:
IllegalStateException,IllegalArgumentException,IOException, or a domain-specific exception class. -
Use Kotlin’s
error("msg")(which throwsIllegalStateException) for unreachable code or invariant violations. -
When wrapping a third-party exception, choose a type that fits the failure category in your own domain.