Using a try-catch block for NullPointerException as a substitute for proper null checks is an anti-pattern. This approach masks the root cause of null pointer dereferences instead of preventing them, leading to unstable and difficult-to-debug code.
Developers sometimes catch NullPointerException for three main reasons, but only one is valid. The first, and most problematic, is using the catch block to handle an existing null dereference bug instead of fixing it with proper validation. The second is explicitly throwing the exception to signal an error, which is misleading as it's designed for runtime detection, not control flow. The only acceptable use is within a testing framework that intentionally generates invalid inputs to verify robustness. Relying on exception handling for normal program logic creates fragile code that obscures the actual source of null values. Instead, you should proactively prevent null dereferences by validating arguments, using optional types, or employing safe navigation operators provided by your language. This makes the code's intent clear, improves performance by avoiding expensive exception overhead, and results in more maintainable and predictable software.
Impact: DoS: Resource Consumption (CPU)
java