LibJF/libjf-base/src/main/java/io/gitlab/jfronny/libjf/generic/Try.java

35 lines
963 B
Java
Raw Normal View History

package io.gitlab.jfronny.libjf.generic;
2022-03-31 20:45:10 +02:00
import java.util.function.Consumer;
import java.util.function.Function;
public class Try {
public static void orElse(ThrowingRunnable<?> tr, Consumer<Throwable> alternative) {
tr.addHandler(alternative).run();
2022-03-31 20:45:10 +02:00
}
2022-04-22 19:18:17 +02:00
public static <T> T orElse(ThrowingSupplier<T, ?> tr, Function<Throwable, ? extends T> alternative) {
return tr.addHandler(alternative).get();
2022-03-31 20:45:10 +02:00
}
2022-04-22 19:18:17 +02:00
public static void orThrow(ThrowingRunnable<?> tr) {
try {
tr.run();
} catch (Throwable e) {
throw runtimeException(e);
}
}
public static <T> T orThrow(ThrowingSupplier<T, ?> tr) {
try {
return tr.get();
} catch (Throwable e) {
throw runtimeException(e);
}
}
protected static RuntimeException runtimeException(Throwable t) {
return t instanceof RuntimeException e ? e : new RuntimeException(t);
}
2022-03-31 20:45:10 +02:00
}