private static <X extends Throwable> CheckedSupplier<Void, X> toVoidSupplier(CheckedRunnable<X> r) { return () -> { r.run(); return null; }; }
/** * Functional variant of the try-catch statement. * * @param errorProneRunnable A {@link CheckedRunnable} to try. * @param onError The {@link Throwable} {@link Consumer} that will handle any exceptions. */ public static void tryCatch(CheckedRunnable<?> errorProneRunnable, Consumer<Throwable> onError) { try { errorProneRunnable.run(); } catch (Throwable e) { onError.accept(e); } }
public static boolean runUninterruptedly(CheckedRunnable<InterruptedException> interruptible) { try { interruptible.run(); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } }
public static <X extends Throwable> long tookNanos(CheckedRunnable<X> r) throws X { final long started = System.nanoTime(); r.run(); return System.nanoTime() - started; } }
public List<Summary> test() throws Throwable { final List<Summary> summaries = new ArrayList<>(times); try { for (int i = 0; i < times; i++) { summaries.add(spec.test()); } } finally { onFinally.run(); } return summaries; } }
private static void doWithExceptionHandler(CheckedRunnable<?> r, ExceptionHandler errorHandler, String message) { try { r.run(); } catch (Throwable e) { errorHandler.onException(message, e); } }
/** * 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); }
/** * Evaluates the given {@code runnable}. If an exception is generated, it will be wrapped using the * thrown exception using the specified {@code wrapper}. * * @param <X> Exception type. * @param runnable The runnable whose exceptions 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 <X extends Throwable> void wrap(CheckedRunnable<?> runnable, Function<Throwable, ? extends X> wrapper) throws X { wrap(() -> { runnable.run(); return null; }, wrapper); }