簡(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