title: When is handling a null pointer/reference exception preferred over doing a null check?
body: <p>I have an odd question that I have always thought about, but could never see a practical use for.  I'm looking to see if there would be enough justification for this.</p>
  
  <p><strong>When is handling a null pointer/reference exception preferred over doing a null check?  If at all.</strong></p>
  
  <p>This applies to any language that has to deal with null pointers/references which has exception handling features.</p>
  
  <p>My usual response to this would be to perform a null check before doing anything with the pointer/reference.  If non-null, continue like normal and use it.  If null, handle the error or raise it.</p>
  
  <p>i.e., (in C#)</p>
  
  
  
  <pre class="lang-c# prettyprint-override"><code>string str = null;
  if (str == null)
  {
      // error!
  }
  else
  {
      // do stuff
      int length = str.Length;
      // ...
  }
  </code></pre>
  
  <p>However if we were not to do the check and just blindly use it, an exception would be raised.</p>
  
  
  
  <pre class="lang-c# prettyprint-override"><code>string str = null;
  int length = str.Length; // oops, NullReferenceException
  // ...
  </code></pre>
  
  <p>Being an exception, we could certainly catch it so nothing is stopping us from doing this (or is there?):</p>
  
  
  
  <pre class="lang-c# prettyprint-override"><code>string str = null;
  try
  {
      int length = str.Length; // oops, NullReferenceException
      // ...
  }
  catch (NullReferenceException ex)
  {
      // but that's ok, we can handle it now
  }
  </code></pre>
  
  <p>Now I admit, it's not the cleanest code, but it's no less working code and I wouldn't do this normally.  But is there a design pattern or something where doing this is useful?  Perhaps more useful than doing the straight up, null check beforehand.</p>
  
  <p>The only cases where I can imagine this might be useful is in a multi-threaded environment where an unprotected shared variable gets set to null too soon.  But how often does that happen?  Good code that protects the variables wouldn't have that problem.  Or possibly if one was writing a debugger and wanted the exception to be thrown explicitly only to wrap it or whatnot.  Maybe an unseen performance benefit or removes the need for other things in the code?</p>
  
  <p>I might have answered some of my questions there but is there any other use to doing this?  I'm not looking for, "do this just because we can" kinds of examples or just poorly written code, but practical uses for it.  Though I'll be ok with, "there's no practical use for it, do the check."</p>