Java 8 Friday:更好的异常
在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
總結
以上是生活随笔為你收集整理的Java 8 Friday:更好的异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人身受到威胁可以备案吗(受到威胁可以备案
- 下一篇: 休眠和UUID标识符