title: Is 1/0 a legal Java expression?
body: <p>The following compiles fine in my Eclipse:</p>
  
  <pre><code>final int j = 1/0;
  // compiles fine!!!
  // throws ArithmeticException: / by zero at run-time
  </code></pre>
  
  <p>Java prevents many "dumb code" from even compiling in the first place (e.g. <code>"Five" instanceof Number</code> doesn't compile!), so the fact this didn't even generate as much as a warning was very surprising to me. The intrigue deepens when you consider the fact that constant expressions are allowed to be optimized at compile time:</p>
  
  <pre><code>public class Div0 {
      public static void main(String[] args) {
          final int i = 2+3;
          final int j = 1/0;
          final int k = 9/2;
      }
  }
  </code></pre>
  
  <p>Compiled in Eclipse, the above snippet generates the following bytecode (<code>javap -c Div0</code>)</p>
  
  <pre><code>Compiled from "Div0.java"
  public class Div0 extends java.lang.Object{
  public Div0();
    Code:
     0:   aload_0
     1:   invokespecial   #8; //Method java/lang/Object."&lt;init&gt;":()V
     4:   return
  
  public static void main(java.lang.String[]);
    Code:
     0:   iconst_5
     1:   istore_1      // "i = 5;"
     2:   iconst_1
     3:   iconst_0
     4:   idiv
     5:   istore_2      // "j = 1/0;"
     6:   iconst_4
     7:   istore_3      // "k = 4;"
     8:   return
  
  }
  </code></pre>
  
  <p>As you can see, the <code>i</code> and <code>k</code> assignments are optimized as compile-time constants, but the division by <code>0</code> (which must've been detectable at compile-time) is simply compiled as is.</p>
  
  <p><code>javac 1.6.0_17</code> behaves even more strangely, compiling silently but excising the assignments to <code>i</code> and <code>k</code> completely out of the bytecode (probably because it determined that they're not used anywhere) but leaving the <code>1/0</code> intact (since removing it would cause an entirely different program semantics).</p>
  
  <p>So the questions are:</p>
  
  <ul>
  <li>Is <code>1/0</code> actually a legal Java expression that should compile anytime anywhere?
  
  <ul>
  <li>What does JLS say about it?</li>
  </ul></li>
  <li>If this is legal, is there a good reason for it?
  
  <ul>
  <li>What good could this possibly serve?</li>
  </ul></li>
  </ul>