java - How to handle IOException in Iterable.forEach? -
i playing around ways write set of objects file. why below implementation using iterable.foreach() not compile? in eclipse, message ioexception not being handled. particularly confusing since appear handling ioexceptions.
public void write(iterable<?> objects) { try (bufferedwriter bw = new bufferedwriter( new outputstreamwriter( new fileoutputstream("out.txt"), "utf-8"));) { objects.foreach((o) -> bw.write(o.tostring())); //unhandled exception type ioexception } catch (ioexception e) { //handle exception } } obviously, below works. i'm interested in why above doesn't work , how fix it.
for (object o : objects) { bw.write(o.tostring()); } i've checked consumer , iterable documentation, , neither of them seem suggest how solve this.
precursor: the catch or specify requirement.
let's write lambda anonymous class:
objects.foreach(new consumer<object>() { public void accept(object o) { bw.write(o.tostring()); } }); are handling it? should clear not.
when write lambda expression, declaring body of method. can't declare throws clause lambda.
the "way around it" following:
try (bufferedwriter bw = new bufferedwriter( new outputstreamwriter( new fileoutputstream("out.txt"), "utf-8"));) { objects.foreach((o) -> { try { bw.write(o.tostring())); } catch(ioexception kludgy) { throw new runtimeexception(kludgy); } }); } catch (runtimeexception kludgy) { throwable cause = kludgy.getcause(); if ( cause instanceof ioexception ) { ioexception e = (ioexception) cause; // handle exception } else { throw kludgy; } } but not good.
instead, don't use foreach in context throws checked exception, or catch exception in body of lambda.
Comments
Post a Comment