Java throw Exception實現異常轉換
簡介
之前的文章我們講到,在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。
接下來看下具體的使用:
@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");
}
}
上面的例子中,我們將一個IOException轉換成了一個unchecked exception。
總結
本文介紹了一種特殊的異常轉換的例子,大家可以參考一下。
本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/rethrow-exception
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springboot實現string轉json json里面帶數組
這篇文章主要介紹了springboot實現string轉json json里面帶數組,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
springboot中使用redis并且執(zhí)行調試lua腳本
今天有個項目需要使用redis,并且有使用腳本的需求,本文主要介紹了springboot中使用redis并且執(zhí)行調試lua腳本,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-04-04

