java關(guān)于throw Exception的一個(gè)小秘密
簡(jiǎn)介
之前的文章我們講到,在stream中處理異常陶贼,需要將checked exception轉(zhuǎn)換為unchecked exception來(lái)處理。
我們是這樣做的:
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)問(wèn)題季蚂,那么有沒(méi)有什么更好的辦法勿决?
throw小訣竅
java的類型推斷大家應(yīng)該都知道乒躺,如果是<T extends Throwable> 這樣的形式,那么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顶籽。
接下來(lái)看下具體的使用:
@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)換的例子礼饱,大家可以參考一下。
本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/rethrow-exception
歡迎關(guān)注我的公眾號(hào):程序那些事究驴,更多精彩等著您镊绪!
更多內(nèi)容請(qǐng)?jiān)L問(wèn) www.flydean.com