title: Java throwing Error and catching NullPointerException
body: <p>This is something that doesn't make sense to me. </p>
  
  <p>First example:</p>
  
  <p>EXAMPLE 1 (GOOD):</p>
  
  <pre><code>public static void main(String args[]){
          try {
              Exception e = null;
              throw e;
          } catch (Exception e) {
          }
  </code></pre>
  
  <p>Everything is fine with ths code - exception is thrown and catched.</p>
  
  <p>EXAMPLE 2 (BAD):</p>
  
  <pre><code>public static void main(String args[]){
      try {
          Exception e = null;
          throw e;
      } catch (NullPointerException e) {
      }
  }
  </code></pre>
  
  <p>This will not compile because catch block can't catch <code>NullPointerException</code> which is subclass of <code>Exception</code>. It doesn't know what kind of exception will be thrown. </p>
  
  <pre><code>java.lang.Object
      java.lang.Throwable
          java.lang.Exception  --&gt; Thrown
              java.lang.RuntimeException
                  java.lang.NullPointerException  --&gt; Cannot catch like this
  </code></pre>
  
  <p>So let's change exception to <code>NullPointerException</code>:</p>
  
  <p>EXAMPLE 3 (GOOD)</p>
  
  <pre><code>public static void main(String args[]) {
      try {
          NullPointerException e = null;
          throw e;
      } catch (NullPointerException e) {
      }
  </code></pre>
  
  <p>Simple and logical, But here comes something really weird:</p>
  
  <p>EXAMPLE 4 (GOOD) - no idea why ?:</p>
  
  <pre><code>public static void main(String args[]) {
      try {
          Error e = null;
          throw e;
      } catch (NullPointerException e) {
      }
  </code></pre>
  
  <p>If I throw an <code>Error</code>, how can I catch <code>NullPointerException</code>? It makes no sense. </p>
  
  <p>There is:</p>
  
  <p>Throwable: Error, Exception</p>
  
  <p>Both <code>Error</code> and <code>Exception</code> are sub-classes of <code>Throwable</code>, but <code>NullPoinTerException</code> has nothing to with <code>Error</code>, it's an <code>Exception</code>, not <code>Error</code>.</p>