title: More efficient way to check neighbours in a two-dimensional array in Java
body: <p>Hey all, for a few of my college assignments I've found the need to check neighbouring cells in 2-dimensional arrays (grids). The solution I've used is a bit of a hack using exceptions, and I'm looking for a way to clean it up without having loads of <code>if</code> statements like some of my classmates. My current solution is</p>
  
  <pre><code>for ( int row = 0; row &lt; grid.length; row++ ) {
      for ( int col = 0; col &lt; grid.length; col++ ) {
          // this section will usually be in a function
          // checks neighbours of the current "cell"
          try {
              for ( int rowMod = -1; rowMod &lt;= 1; rowMod++ ) {
                  for ( int colMod = -1; colMod &lt;= 1; colMod++ ) {
                      if ( someVar == grid[row+rowMod][col+colMod] ) {
                          // do something
                      }
                  }
              }
          } catch ( ArrayIndexOutOfBoundsException e ) {
              // do nothing, continue
          }
          // end checking neighbours
      }
  }
  </code></pre>
  
  <p>I shudder to think of the inefficiency using exceptions to get my code to work causes, so I'm looking for suggestions as to how I could remove the reliance on exceptions from my code without sacrificing readability if it's possible, and just how I could make this code segment generally more efficient. Thanks in advance.</p>