How do I prevent a Java NullPointerException instead of just catching it?
- Expert answer
- Undergraduate
- Asked
The question
My Java project keeps throwing NullPointerException when a customer has no address. I wrapped the code in try/catch and it stopped crashing, but my tutor said catching NPEs is bad practice.
Short answer
An NPE is a bug signal, so catching it hides the cause. Decide whether null is a valid state. If it is, model it explicitly with checks or Optional. If it is not, stop it at the source with constructor validation such as Objects.requireNonNull.
Full expert answer
Java tutor
BSc Software Engineering, Oracle Certified Professional
Your tutor is right. A NullPointerException means the program reached a state you did not plan for. Catching it keeps the program running in that unplanned state, which usually causes a more confusing failure later.
First decide: is null allowed?
A customer with no address may be perfectly valid, for instance an online-only account. Or it may be a data error. The fix is different in each case, and explaining that decision in your report is worth marks.
If null is valid
- Return Optional<Address> from getAddress() so callers must handle the empty case
- Use address.map(Address::getPostcode).orElse("Not provided") rather than chained calls
- Or check explicitly with if (address != null) at the one place it is used
If null is not valid
- Validate in the constructor with Objects.requireNonNull(address, "address must not be null")
- The program then fails immediately, at the line that created the bad object, with a clear message
- Add a unit test that confirms invalid construction throws
This answer explains a method for you to apply to your own work. Copying it into a submission would count as plagiarism, and it is indexed by similarity checkers.
All questions