(资料图)
平时开发中,我们经常会处理一些不得不处理的检查性异常以及一些无关紧要的一场,例如:
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
});public class Catcher {
List> classes = new LinkedList<>();
private Action action;
private Catcher(List> list) {
classes.addAll(list);
}
@SafeVarargs
public static Catcher capture(Class extends T>... 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使用Catcher捕获异常的实现的文章就介绍到这了,更多相关Java Catcher捕获异常内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
关键词:
为贯彻落实中国人民银行、国家外汇管理局惠企利民纾困23条政策,加大个体工商户金融支持力度,5月10日,记者从人民银行成都分行获悉,该行
近日,中办、国办印发《关于推进以县城为重要载体的城镇化建设的意见》。意见指出,县城是城乡融合发展的重要支撑,要推进新型城镇化建设,
据安徽省马鞍山市新冠肺炎疫情防控应急综合指挥部3月30日通报:截至30日21时,马鞍山市新增2例无症状感染者,系省外返马人员,在高速卡