There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.
Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?
Best Answer
If you're using third party code that is returning
null
, it's much better to check the return value.Edit: Java 8 is out! This should now be
A
NullPointerException
is insidious and misleading, because it means you have an error somewhere else, where a variable was set tonull
without you expecting it to be.I repeat, the bug isn't where the
NullPointerException
was thrown, the bug is earlier in your code, where a variable was set tonull
without you expecting it to be.Catching the
NullPointerException
means you're hiding or excusing the actual bug.In your own code, it is much better to do away with
null
whereever possible, and for that matter, also mutable variables.If you get an exception, don't catch it and return
null
, instead wrap and rethrow the exception.If you have a method that should sometimes not return a value, you could return an empty
Collection
, or an Optional, which is new in Java 8.If you never set a variable to
null
you can never have an unexpectednull
.Don't allow
null
parameters:Avoid creating "result" variables that are temporarily
null
:Instead of:
you should:
Sooner or later you will start to see usage of
null
(and mutable variables) as a code smell.I'm sure you can come up with other smart ways to avoid
null
, be creative!tl;dr:
NullPointerException
should never be thrown in the first place, so don't catch it, because that means you're hiding the actual bug.