2

I have a very simple method:

public int getScore() {
    return game.gameWindow.userBestScore;
}

The problem is that it can happens that game object or gameWindow do not exist. I do not want to get the Null Pointer Exception. How can catch it in a correct way? Can I do it in this way:

   public int getScore() {
         try{
             return game.gameWindow.userBestScore;
          } catch(NullPointerException e){
              return -1;
          }
   }
CharithJ
  • 46,289
  • 20
  • 116
  • 131
Roman
  • 124,451
  • 167
  • 349
  • 456

6 Answers6

12

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.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
2

You can do that. You can also check to see if game and gameWindow are null before trying to access userBestScore.

if(game != null && game.gameWindow != null)
    return game.gameWindow.userBestScore
2

Check whether the variables are null as shown below:

public int getScore() {
    if(game == null || game.gameWindow == null){
        return -1;
    }
    return game.gameWindow.userBestScore;
}
dogbane
  • 266,786
  • 75
  • 396
  • 414
2
public int getScore() {
    return ((game == null || game.gameWindow == null) ? -1 : game.gameWindow.userBestScore);
}
Vaandu
  • 4,857
  • 12
  • 49
  • 75
1

You can do that. OR you can check for null before you dereference those objects and take appropriate action without throwing an exception. That'll be more efficient.

The real question you should be asking is: Why on earth would an object have null references for private data members? You aren't constructing your objects properly. An object should be properly initialized and 100% ready to go after you create it. Otherwise, you end up having to be unnecessarily defensive in your code.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Bit of a sweeping generalisation. There's loads of reasons why an object might have null references for private members – Steve Sep 30 '11 at 13:44
  • Would you agree that improper initialization would be on the list? If yes, please list some of the others, because I don't see "loads". I would imaging less than half a dozen without thinking too hard about it. Yours is the more sweeping statement, with less substantiation. – duffymo Oct 01 '11 at 02:20
  • The fact that you've gone from "Why on Earth..." to maybe a dozen reasons proves my point enough. Didn't mean to offend by the way, liked your answer for the most part ;) – Steve Oct 03 '11 at 16:58
  • Half a dozen is not a dozen. I'm not offended - I'm expressing an opinion. – duffymo Oct 04 '11 at 22:27
0

Avoid exception throwing as much as possible. Handling the known issues is the better way than throwing exceptions.

In some where you have to do a null check. Probably before calling the getScore() method, because that doesn't make a sense of calling that method if the game or gameWindow is null.

if (game != null && gameWindow != null)
{
    int score = getScore();
}

OR

public int getScore() 
{
    if (game != null && gameWindow != null)
    {
       return game.gameWindow.userBestScore;
    }
    else
    {
        return -1;
    }
}

Don't do duplicate null checkings.

CharithJ
  • 46,289
  • 20
  • 116
  • 131