No Catch NPE
ID |
kotlin.no_catch_npe |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Kotlin |
Tags |
CWE:395, catch, exception, null-safety |
Description
Reports catch (e: NullPointerException) blocks. Catching the NPE masks a real bug
(a forgotten non-null check, an incorrect platform-type cast) instead of fixing it.
Rationale
// Bad
try { foo.bar() } catch (e: NullPointerException) { ... } // FLAW
try { foo.bar() } catch (e: java.lang.NullPointerException) { ... } // FLAW
// Good — use Kotlin null-safety operators
foo?.bar()
foo?.bar() ?: defaultValue
requireNotNull(foo) { "foo must not be null" }.bar()
Once an NPE has been thrown, the underlying state is already inconsistent. The catch keeps the bug alive and makes diagnosis harder because the actual null source is buried in the stack trace rather than at the call site.
Remediation
-
Use the safe-call operator
?.to short-circuit when a value may be null. -
Use the Elvis operator
?:to supply a default for null values. -
Use
requireNotNull(value) { msg }to fail fast with a descriptive message at the call site. -
Declare types as nullable (
String?) where null is a legitimate value.