Class ExceptionHandler

  • @ApiIssue("GitHub issue #3: Add wrapped(), sneaked(), and checked(handler) that return CombinedExceptionHandler (checked -> optional).") @ApiIssue("Add only/except(Predicate<Throwable>), which return handler that rethrows selected exceptions without passing them to handle().")
    public abstract class ExceptionHandler
    extends Object
    Represents exception handling policy. Methods of this class apply the exception policy to functional interfaces (usually lambdas) by wrapping them in a try-catch block. Method handle(Throwable) defines the exception handling policy when implemented in derived class. See noexception tutorial.

    Typical usage: Exceptions.silence().get(() -> my_throwing_lambda).orElse(fallback)

    All wrapping methods surround the functional interface with a try-catch block. If the functional interface throws, the exception is caught and passed to handle(Throwable), which applies exception handling policy (silence, propagate, logging, custom). NullPointerException from null functional interface is caught too. Unless handle(Throwable) requests a rethrow, void functional interfaces complete normally while non-void functional interfaces return empty Optional.

    Wrapping methods for all standard functional interfaces are provided. Simple interfaces have short method names like runnable(Runnable) or supplier(Supplier). Interfaces with longer names have methods that follow fromX naming pattern, for example fromUnaryOperator(UnaryOperator). Parameterless functional interfaces can be called directly by methods run(Runnable), get(Supplier), and the various getAsX variants.

    All non-void wrappers conform to some OptionalX functional interface, for example OptionalSupplier, that is identical to its non-optional variant from JDK except it returns Optional instead of raw value. This Optional is empty in case of exception. Callers can use Optional.orElse(Object) and Optional.orElseGet(Supplier) and their equivalents on OptionalX interfaces to provide fallback values.

    See Also:
    Tutorial, handle(Throwable), Exceptions, OptionalSupplier, Optional, ExceptionFilter, CheckedExceptionHandler