No Throw NPE
ID |
kotlin.no_throw_npe |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Kotlin |
Tags |
CWE:248, error-handling, exception |
Description
Reports throw NullPointerException(…) expressions. The NPE exception type is
reserved, by convention, for the JVM to signal an unintended dereference of a null
reference. Code that explicitly throws an NPE conflates an unexpected programming error
with an intentional control-flow signal, making the resulting stack traces harder to
read and bug reports harder to triage.
Rationale
Throwing NullPointerException from application code is misleading: readers expect any
NPE in a stack trace to mark an unintentional crash. The Kotlin standard library provides
purpose-built helpers — requireNotNull(value), checkNotNull(value), error("…") —
that document intent and produce a contextual message. For bad arguments or state
invariants, IllegalArgumentException and IllegalStateException (or require and
check) are the right exception types.
// Bad
throw NullPointerException("user must not be null") // FLAW
throw java.lang.NullPointerException() // FLAW
// Good
throw IllegalStateException("user must not be null")
requireNotNull(user) { "user must not be null" }
checkNotNull(session)