Skip to content

Instantly share code, notes, and snippets.

@ovstetun
Last active September 21, 2016 12:45
Show Gist options
  • Save ovstetun/e84bc62b52abed933646 to your computer and use it in GitHub Desktop.
Save ovstetun/e84bc62b52abed933646 to your computer and use it in GitHub Desktop.
exceptionwrapping
Runtime.getRuntime().addShutdownHook(new Thread(() -> consumer(server::close)));
File tempFile = propagate(() -> File.createTempFile("util-tests", ".tmp"));
public class Java8Util {
public static interface ExceptionWrapper<E> {
E wrap(Exception e);
}
public static <T> T propagate(Callable<T> callable) throws RuntimeException {
return propagate(callable, RuntimeException::new);
}
public static <T, E extends Throwable> T propagate(Callable<T> callable, ExceptionWrapper<E> wrapper) throws E {
try {
return callable.call();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw wrapper.wrap(e);
}
}
public interface RunnableWithException {
public void run() throws Exception;
}
public static void consumer(RunnableWithException runnable) throws RuntimeException {
consumer(runnable, RuntimeException::new);
}
public static void consumer(RunnableWithException runnable, ExceptionWrapper<RuntimeException> wrapper) {
try {
runnable.run();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw wrapper.wrap(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment