Java Reference
In-Depth Information
file = Optional.of(File.createTempFile("funfile", "tmp"));
return file.map(function).get();
} catch (IOException e) {
return exceptionHandler.apply(e);
} finally {
file.ifPresent(File::delete);
}
}
Exception Handling via Output: Capturing Execution Results
It's not how people normally think of it, but you can consider the checked exception to be a part of the
API of the method. Think of it in terms of postconditions: when the method execution completes, either
the method will have returned a value or it will have thrown an exception. Being good object-oriented
programmers, you can encapsulate those alternatives into an object. The result is a more functional (and
function-friendly) style of programming.
The first thing that we will need is a class to capture these results. We could use the Optional class,
but it does not have a way to communicate what the exception was. So let's build out something like the
Optional class, but optionally containing our exception. We can call it our Result class. But before we use it,
let's understand what we're using. Listing 4-2 contains the entire class definition, but don't let it scare you:
we will walk through it piece by piece, and it is actually quite simple. In the process, we will also get to see
the power of the Optional class's API.
Listing 4-2. The Result Class
import java.util.*;
import java.util.function.*;
/**
* A class which represents a result of some processing, which is either
* an exception or an object of the given type.
*/
public class Result<RESULT_T> {
private final Optional<RESULT_T> result;
private final Optional<Exception> exception;
/**
* Constructs an instance to wrap the given result.
*
* @param result The result; may not be {@code null}
*/
public Result(RESULT_T result) {
Objects.requireNonNull(result, "result to wrap");
this.result = Optional.of(result);
this.exception = Optional.empty();
}
/**
* Constructs an instance to wrap the given exception.
*
 
Search WWH ::




Custom Search