Java Reference
In-Depth Information
if (i == 100) {
throw new IOException(
"And with a kiss, I die! (After " + count + " executions)");
}
return i;
};
}
public static void main(String[] args) {
// Create the handler for exceptions
ResourceExceptionHandler handler =
new ResourceExceptionHandler(Listing5::generateInputStream);
// Perform the stream processing
Function<Integer, Stream<Integer>> flatMapFunction =
handler.map(generateMap());
generateParallelStream()
.flatMap(flatMapFunction)
.forEach(System.out::println);
// Work with the exceptions
Map<Object, Exception> exceptions = handler.getExceptions();
exceptions.forEach((key, val) -> {
System.out.println(key + ": " + val);
val.printStackTrace(System.err);
}
);
}
}
In both of these cases, we have a nice separation of concerns: our stream works the happy path, and
then we deal with the exceptions later on. The code itself is rather ugly and touchy, which is why it is best to
write it once and be done with it. The APIs provided above, along with others, are available in the FunJava
project under the name funjava.io.FunResource .
While this approach provides the clear distinction between the “happy path” of the stream and
exception handling later on, sometimes that distinction cannot be kept clear. Sometimes you want to be
able to handle exceptions as part of the processing. In that case, you want to keep the information about the
exception within the same stream. This is the point when we use a Result object.
Handling Resources Using a Result Object
Consider a stream where you want to process files. The files, however, may or may not exist, and if they do
not exist, that has a specific meaning, as well. For instance, the files may be optional user-specified files, and
if the file is not uploaded, then you want to use a default. In this case, you will want to keep the information
about an IO error within the stream itself, so that you can process that error within the stream. This makes
the handler approach we saw in the last section ill-suited, because you do not want to be querying another
object to find out what happened earlier in the same stream. The unchecked exception situation would
break consistently and get you nowhere. Instead, what you are looking for is a Result object.
 
Search WWH ::




Custom Search