Do not catch a NullPointerException
.
A NullPointerException
is a sign that your code is not adhering to some contract. If it is possible that game
can be null
, then you need to make an explicit test:
if(game != null) {
...
}
else {
...
}
If game
should not be null, then you can ensure the correctness of your code by using assert
.
assert game != null;
...
What is more worrying is that game
seems to be a private member of your class. In this case game
should probably not be null
(although there are cases where this can happen). Are you initializing it properly in your constructor? I'd say that the first thing you should is to make sure that game
is being initialized properly. Otherwise your code will end up being littered with un-necessary null
-checks. For example, what if gameWindow
in the Game
class wasn't initialized properly? You would need to have another null
-check for that:
if(game !== null && game.gameWindow != null) {
...
}
else {
...
}
So you should first make sure that your object's private members are being initialized properly. If they are, and it turns out that there is a valid use-case for game
being null
, then you would need an explicit null-
check. It's always better to test for null
than catching a NullPointerException
. Other than the fact that exceptions should not be used to control the flow of your business logic, what if a valid NullPointerException
(due to a programming error) was generated somewhere up the chain? Now your catch
will catch it and you won't know about it; this can lead to some really nasty and hard-to-find bugs.