Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload