public static void main(String[] args) throws Throwable { CheckedRunnable checkedRunnable = () -> { File file = new File("/Users/vinayprajapati/Desktop/project/jool-hands-on/src/main/java/jool/features/analysis/fi/TestCheckedRunnable.java"); InputStream inputStream = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; inputStream.read(data); inputStream.close(); String str = new String(data, "UTF-8"); System.out.println(str); }; checkedRunnable.run(); //Sufficient to show should be used only when Runnable exected to throw checked exception }
@Test public void testCheckedRunnable() { final CheckedRunnable runnable = () -> { throw new Exception("runnable"); }; Runnable r1 = Unchecked.runnable(runnable); Runnable r2 = CheckedRunnable.unchecked(runnable); Runnable r3 = Sneaky.runnable(runnable); Runnable r4 = CheckedRunnable.sneaky(runnable); assertRunnable(r1, UncheckedException.class); assertRunnable(r2, UncheckedException.class); assertRunnable(r3, Exception.class); assertRunnable(r4, Exception.class); }
/** * Assert a Throwable type and implement more assertions in a consumer */ public static void assertThrows(Class<?> throwable, CheckedRunnable runnable, Consumer<Throwable> exceptionConsumer) { boolean fail = false; try { runnable.run(); fail = true; } catch (Throwable t) { if (!throwable.isInstance(t)) throw new AssertionError("Bad exception type", t); exceptionConsumer.accept(t); } if (fail) Assert.fail("No exception was thrown"); }
static void runAndWait(Runnable runnable) { if (isSupported()) { CountDownLatch latch = new CountDownLatch(1); AlchemyThreadManager.runOnNewThread(link(JFXPanel::new, () -> Platform.runLater(link(runnable, latch::countDown)))); CheckedRunnable.unchecked(latch::await, AlchemyRuntimeException::onException).run(); } }
private void silentClose(CheckedRunnable c) { CompletableFuture completableFuture = new CompletableFuture(); try { c.run(); completableFuture.complete(true); } catch (Throwable e) { completableFuture.completeExceptionally(e); } completableFutures.add(completableFuture); }
public static <T extends AutoCloseable> void tryWithoutResult(CheckedRunnable f) { try { f.run(); } catch (Throwable e) { throw new IllegalStateException(e); } }
@Test public void testCheckedRunnableWithCustomHandler() { final CheckedRunnable runnable = () -> { throw new Exception("runnable"); }; final Consumer<Throwable> handler = e -> { throw new IllegalStateException(e); }; Runnable test = Unchecked.runnable(runnable, handler); Runnable alias = CheckedRunnable.unchecked(runnable, handler); assertRunnable(test, IllegalStateException.class); assertRunnable(alias, IllegalStateException.class); }
public static void ignoreThrows(CheckedRunnable runnable) { try { runnable.run(); } catch (Throwable t) { t.printStackTrace(); } }
/** * Assert a Throwable type */ public static void assertThrows(Class<?> throwable, CheckedRunnable runnable) { assertThrows(throwable, runnable, t -> {}); }