Throwing Exceptions Without Message
ID |
kotlin.throwing_without_message |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
diagnostics, exception |
Description
Reports throw expressions that construct an exception with no arguments, providing no diagnostic message to callers or log consumers.
When an exception carries no message, the only information available at failure time is the exception type and stack trace. A descriptive message identifies the specific condition that triggered the failure, the values involved, and the corrective action expected, dramatically reducing mean time to diagnose.
Rationale
// Bad — no context; caller and logs get only the type name
fun validate(value: Int) {
if (value < 0) throw IllegalArgumentException() // FLAW
}
fun connect(url: String?) {
checkNotNull(url)
if (!isReachable(url)) throw IllegalStateException() // FLAW
}
// Good — message describes the failure condition
fun validate(value: Int) {
if (value < 0) throw IllegalArgumentException("value must be non-negative, got: $value")
}
fun connect(url: String?) {
checkNotNull(url)
if (!isReachable(url)) throw IllegalStateException("Cannot reach endpoint: $url")
}
// OK — cause chain preserves the original exception context
fun parse(input: String): Int {
try {
return input.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("Invalid integer input: $input", e)
}
}
Remediation
-
Add a descriptive string as the first argument to the exception constructor.
-
Include relevant variable values in the message using string templates (
$variable). -
When wrapping a caught exception, pass it as the
causeparameter to preserve the chain.