开发者

How to catch the exception caused by an absence of an object in Java?

I have a very simp开发者_Go百科le 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;
          }
   }


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.


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


Check whether the variables are null as shown below:

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


public int getScore() {
    return ((game == null || game.gameWindow == null) ? -1 : game.gameWindow.userBestScore);
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜