/** * Closes a given {@link Closeable} instance, wrapping any potential {@link IOException} * in an unchecked {@link RuntimeIOException}. * * @param closeable The {@link Closeable} to close. */ public static void closeUnchecked(Closeable closeable) { Exceptions.wrapStrict(closeable::close, RuntimeIOException::new); } }
/** * Evaluates the given {@code supplier}, returning the supplied value if successful, or otherwise wrapping the * thrown exception using the specified {@code wrapper}. * * @param <T> Return type. * @param <X> Exception type. * @param supplier The supplier whose exceptions to trap. * @param wrapper The handler for trapped exceptions, returning a wrapped exception of type {@code X}. * @return The result of evaluating the supplier. * @throws X If an exception occurs. */ public static <T, X extends Throwable> T wrap(CheckedSupplier<? extends T, ?> supplier, Function<Throwable, ? extends X> wrapper) throws X { return wrapStrict(supplier, wrapper); }
/** * A strict form of {@link #wrap(CheckedRunnable, Function)} that requires that the exception * wrapper takes a subtype of the exception thrown by the runnable block. * * @param <W> Exception type thrown by the runnable, and input to the wrapper. * @param <X> Exception type thrown by the wrapper. * @param runnable The runnable whose exception to trap. * @param wrapper The handler for trapped exceptions, returning a wrapped exception of type {@code X}. * @throws X If an exception occurs. */ public static <W extends Throwable, X extends Throwable> void wrapStrict(CheckedRunnable<? extends W> runnable, Function<? super W, ? extends X> wrapper) throws X { wrapStrict(() -> { runnable.run(); return null; }, wrapper); }