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

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

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

概述

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

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

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

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

實際上,這類代碼我們通常只關(guān)心三個部分:1. 執(zhí)行的動作;2. 和動作關(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的實現(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;
? ? }
}

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

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

相關(guān)文章

最新評論

灵台县| 仁怀市| 临漳县| 江达县| 祥云县| 深州市| 延寿县| 岱山县| 江都市| 东至县| 桦南县| 南投市| 乳源| 广昌县| 桑植县| 米脂县| 抚松县| 临海市| 磴口县| 昌吉市| 元江| 淮南市| 卓资县| 加查县| 许昌县| 娄烦县| 修文县| 仙居县| 杂多县| 沙河市| 红安县| 麻城市| 江华| 海宁市| 石阡县| 丹阳市| 灵川县| 桂东县| 佛坪县| 乐昌市| 新龙县|