title: Java 8 - closing stream on Exception?
body: <p>Is there a way for Stream to be closed if exception will occur during invocation of any element of the built stream chain?</p>
  
  <p>For example, the code:</p>
  
  <pre><code>    Stream.of(new Object())
              .filter(e -&gt; {
                  if (true) throw new IllegalStateException();
                  return true;
              })
              .onClose(() -&gt; System.out.println("OnClose"))
              .collect(Collectors.toList());
  </code></pre>
  
  <p>will produce the following output:</p>
  
  <pre><code>Exception in thread "main" java.lang.IllegalStateException
  at my.className.lambda$main$2(LdapRealm.java:114)
  at my.className$$Lambda$1/1607521710.test(Unknown Source)
  at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
  at java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:419)
  at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
  at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
  at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
  at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
  at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
  at my.className.main(LdapRealm.java:118)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:483)
  at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
  </code></pre>
  
  <p>Note that "OnClose" message was not printed because onClose() haven't been called. Is there any good solution for this problem if I want this stream to be used by third party code and I don't sure if that code will facilitate <code>try/catch</code>+<code>Autocloseable</code> feature?</p>