title: Java8 Lambdas and Exceptions
body: <p>I wonder if someone could explain the following weirdness to me. I'm using Java 8 update 11.</p>
  
  <p>Given this method</p>
  
  <pre><code>private &lt;F,T&gt; T runFun(Function&lt;Optional&lt;F&gt;, T&gt; fun, Optional&lt;F&gt; opt) {
     return fun.apply(opt) ;
  }
  </code></pre>
  
  <p>If I first construct a function Object, and pass that in to the method above, things compile.</p>
  
  <pre><code>private void doesCompile() {
      Function&lt;Optional&lt;String&gt;, String&gt; fun = o -&gt; o.orElseThrow(() -&gt; new RuntimeException("nah"));
      runFun(fun, Optional.of("foo"));
  
  }
  </code></pre>
  
  <p>But, if I inline the function as a lambda, the compiler says </p>
  
  <blockquote>
    <p>unreported exception X; must be caught or declared to be thrown</p>
  </blockquote>
  
  <pre><code>private void doesNotCompile () {
      runFun(o -&gt; o.orElseThrow(() -&gt; new RuntimeException("nah")), Optional.of("foo"));
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Update</strong>:
  Turns out the error message was abbreviated by maven. If compiled directly with javac, the error is:</p>
  
  <pre><code>error: unreported exception X; must be caught or declared to be thrown
              runFun(o -&gt; o.orElseThrow(() -&gt; new RuntimeException("nah")), Optional.of("foo"));
                                       ^
    where X,T are type-variables:
      X extends Throwable declared in method &lt;X&gt;orElseThrow(Supplier&lt;? extends X&gt;)
      T extends Object declared in class Optional
  </code></pre>
  
  <p>Also see <a href="https://gist.github.com/rompetroll/667bf46ac0168a92497a" rel="noreferrer">here</a> for runnable test code.</p>