java關(guān)于throw Exception的一個(gè)小秘密

簡(jiǎn)介

之前的文章我們講到,在stream中處理異常,需要將checked exception轉(zhuǎn)換為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感覺總是有那么一點(diǎn)點(diǎn)問題,那么有沒有什么更好的辦法?
throw小訣竅

java的類型推斷大家應(yīng)該都知道,如果是 這樣的形式,那么T將會(huì)被認(rèn)為是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
    }

}

上面的類中,我們定義了一個(gè)throwException方法,接收一個(gè)Exception參數(shù),將其轉(zhuǎn)換為T,這里的T就是unchecked exception。

接下來看下具體的使用:

@Slf4j
public 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");
    }
}

上面的例子中,我們將一個(gè)IOException轉(zhuǎn)換成了一個(gè)unchecked exception。
總結(jié)

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

愿與諸君共進(jìn)步,大量的面試題及答案還有資深架構(gòu)師錄制的視頻錄像:有Spring,MyBatis,Netty源碼分析,高并發(fā)、高性能、分布式、微服務(wù)架構(gòu)的原理,JVM性能優(yōu)化、分布式架構(gòu)等這些成為架構(gòu)師必備的知識(shí)體系,可以微信搜索539413949獲取,最后祝大家都能拿到自己心儀的offer

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容