您的位置:首頁技術文章
文章詳情頁

Java throw Exception實現異常轉換

瀏覽:2日期:2022-09-02 13:39:47

簡介

之前的文章我們講到,在stream中處理異常,需要將checked exception轉換為unchecked exception來處理。

我們是這樣做的:

static <T> Consumer<T> consumerWrapper( ThrowingConsumer<T, Exception> throwingConsumer) { return i -> { try {throwingConsumer.accept(i); } catch (Exception ex) {throw new RuntimeException(ex); } }; }

將異常捕獲,然后封裝成為RuntimeException。

封裝成RuntimeException感覺總是有那么一點點問題,那么有沒有什么更好的辦法?

throw小訣竅

java的類型推斷大家應該都知道,如果是 這樣的形式,那么T將會被認為是RuntimeException!

我們看下例子:

public class RethrowException { public static <T extends Exception, R> R throwException(Exception t) throws T { throw (T) t; // just throw it, convert checked exception to unchecked exception }}

上面的類中,我們定義了一個throwException方法,接收一個Exception參數,將其轉換為T,這里的T就是unchecked exception。

接下來看下具體的使用:

@Slf4jpublic class RethrowUsage { public static void main(String[] args) { try { throwIOException(); } catch (IOException e) { log.error(e.getMessage(),e); RethrowException.throwException(e); } } static void throwIOException() throws IOException{ throw new IOException('io exception'); }}

上面的例子中,我們將一個IOException轉換成了一個unchecked exception。

總結

本文介紹了一種特殊的異常轉換的例子,大家可以參考一下。

本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/rethrow-exception

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
国产综合久久一区二区三区