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

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

概述

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

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> classes = new LinkedList<>();
    private Action action;
    private   Catcher(List> list) {
        classes.addAll(list);
    }

    @SafeVarargs
    public static  Catcher capture(Class... classes){
        List> list = Arrays.asList(classes);
        return new Catcher(list);
    }

    public Catcher from(Action action){
        this.action = action;
        return this;
    }

    public void to(Consumer 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;
    }
}

你可能感兴趣的:(Java,java,exception,lambda,java,8,函数式编程)