最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java使用Catcher捕獲異常的實(shí)現(xiàn)

 更新時(shí)間:2023年05月12日 15:45:32   作者:樂(lè)征skyline  
本文主要介紹了Java使用Catcher捕獲異常的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

概述

平時(shí)開(kāi)發(fā)中,我們經(jīng)常會(huì)處理一些不得不處理的檢查性異常以及一些無(wú)關(guān)緊要的一場(chǎng),例如:

try {
    doSomething();
} catch (Exception e) {
    e.printStackTrace();
    //or Logger.d("error:" + e.getMessage());
}

即便只是想忽略掉異常也得寫成:

try {
    doSomething();
} catch (Exception ignore) {
}

實(shí)際上,這類代碼我們通常只關(guān)心三個(gè)部分:1. 執(zhí)行的動(dòng)作;2. 和動(dòng)作關(guān)聯(lián)的異常;3. 異常的處理方式。想象中的偽代碼可能是這樣的:

capture IOException?
? ? from () -> {
? ? }
? ? to handleIOException

轉(zhuǎn)換為Java代碼,就是:

Catcher.capture(IllegalAccessException.class)
        .from(() -> {
            //do something
            throw new Exception("kdsfkj");
        }).to(Main::onFailed);
//或
Catcher.capture(IllegalAccessException.class, IOException.class)
        .from(() -> {
            //do something
            throw new Exception("kdsfkj");
        })
        .to(e -> {
            //handle exception
        });

Catcher的實(shí)現(xiàn)

public class Catcher {
? ? List<Class<?>> classes = new LinkedList<>();
? ? private Action action;
? ? private ?<T extends Exception> Catcher(List<Class<? extends T>> list) {
? ? ? ? classes.addAll(list);
? ? }
? ? @SafeVarargs
? ? public static <T extends Exception> Catcher capture(Class<? extends T>... classes){
? ? ? ? List<Class<? extends T>> list = Arrays.asList(classes);
? ? ? ? return new Catcher(list);
? ? }
? ? public Catcher from(Action action){
? ? ? ? this.action = action;
? ? ? ? return this;
? ? }
? ? public void to(Consumer<Exception> exceptionConsumer){
? ? ? ? try {
? ? ? ? ? ? action.run();
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? for(Class<?> mClass : classes){
? ? ? ? ? ? ? ? if(mClass.isInstance(e)){
? ? ? ? ? ? ? ? ? ? exceptionConsumer.accept(e);
? ? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? throw new IllegalStateException(e);
? ? ? ? }
? ? }
? ? public interface Action{
? ? ? ? void run() throws Exception;
? ? }
}

注意:本文所展示的代碼僅用于娛樂(lè)用途,如有啟發(fā),純屬巧合,請(qǐng)勿用在實(shí)際生產(chǎn)環(huán)境

到此這篇關(guān)于Java使用Catcher捕獲異常的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Java Catcher捕獲異常內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

科技| 永川市| 汤阴县| 云林县| 延边| 清涧县| 蓬莱市| 江陵县| 兰考县| 龙山县| 丽水市| 定襄县| 盘锦市| 鄯善县| 昌黎县| 通辽市| 绥化市| 湖州市| 龙井市| 秦皇岛市| 高州市| 靖州| 无为县| 西乌珠穆沁旗| 都匀市| 紫阳县| 昌黎县| 南溪县| 长春市| 吴旗县| 绵阳市| 铅山县| 平湖市| 平凉市| 阿坝县| 沅陵县| 石棉县| 宜都市| 崇文区| 石泉县| 镇赉县|