在Data Geekery ,我们喜欢Java。 而且,由于我们真的很喜欢jOOQ的流畅的API和查询DSL ,我们对Java 8将为我们的生态系统带来什么感到非常兴奋。
Java 8星期五
每个星期五,我们都会向您展示一些不错的教程风格的Java 8新功能,这些功能利用了lambda表达式,扩展方法和其他好东西。 您可以在GitHub上找到源代码 。
更好的例外
当我偶然发现JUnit GitHub问题#706时 ,我有了这个主意,它是关于一个新方法的建议:
ExpectedException#expect(Throwable, Callable)
一种建议是为此类异常创建拦截器。
assertEquals(Exception.class, thrown(() -> foo()).getClass());
assertEquals("yikes!", thrown(() -> foo()).getMessage());
另一方面,为什么不只是按照这种方式添加全新的内容呢?
// This is needed to allow for throwing Throwables
// from lambda expressions
@FunctionalInterface
interface ThrowableRunnable {void run() throws Throwable;
}// Assert a Throwable type
static void assertThrows(Class<? extends Throwable> throwable,ThrowableRunnable runnable
) {assertThrows(throwable, runnable, t -> {});
}// Assert a Throwable type and implement more
// assertions in a consumer
static void assertThrows(Class<? extends Throwable> throwable,ThrowableRunnable runnable,Consumer<Throwable> exceptionConsumer
) {boolean fail = false;try {runnable.run();fail = true;}catch (Throwable t) {if (!throwable.isInstance(t))Assert.fail("Bad exception type");exceptionConsumer.accept(t);}if (fail)Assert.fail("No exception was thrown");
}
因此上述方法都断言从给定的runnable – ThrowableRunnable
抛出了给定的throwable,因为不幸的是,大多数功能接口都不允许抛出检查异常。 有关详细信息,请参见本文 。
现在,我们使用上述假设的JUnit API:
assertThrows(Exception.class, () -> { throw new Exception(); });assertThrows(Exception.class, () -> { throw new Exception("Message"); },e -> assertEquals("Message", e.getMessage()));
实际上,我们甚至可以更进一步,声明一个吞下此类辅助方法的异常,如下所示:
// This essentially swallows exceptions
static void withExceptions(ThrowableRunnable runnable
) {withExceptions(runnable, t -> {});
}// This delegates exception handling to a consumer
static void withExceptions(ThrowableRunnable runnable,Consumer<Throwable> exceptionConsumer
) {try {runnable.run();}catch (Throwable t) {exceptionConsumer.accept(t);}
}
这对于吞噬各种异常很有用。 因此,以下两个习惯用法是等效的:
try {// This will failassertThrows(SQLException.class, () -> {throw new Exception();});
}
catch (Throwable t) {t.printStackTrace();
}withExceptions(// This will fail() -> assertThrows(SQLException.class, () -> {throw new Exception();}),t -> t.printStackTrace()
);
显然,这些习惯用法不一定比实际的try .. catch .. finally
块有用,特别是因为它不支持异常的正确键入(至少在此示例中不支持),也不支持try-with -resources语句。
但是,此类实用程序方法有时会派上用场。
翻译自: https://www.javacodegeeks.com/2014/05/java-8-friday-better-exceptions.html