likes
comments
collection
share

日常调戏Java:用Catcher捕获异常

作者站长头像
站长
· 阅读数 24

注意:本文所展示的代码仅用于娱乐用途,如有启发,纯属巧合,请勿用在实际生产环境

概述

平时开发中,我们经常会处理一些不得不处理的检查性异常以及一些无关紧要的一场,例如:

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

即便只是想忽略掉异常也得写成:

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

实际上,这类代码我们通常只关心三个部分:1. 执行的动作;2. 和动作关联的异常;3. 异常的处理方式。想象中的伪代码可能是这样的:

capture IOException 
    from () -> {

    }
    to handleIOException

转换为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的实现

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;
    }
}