平常开发中,大家常常会处置一些不能不处置的检查性异常与一些不重要的一场,比如:
try{doSomething();}catch(Exceptione){e.printStackTrace();//orLogger.d(error:+e.getMessage());}
即使只不过想忽视掉异常也得写成:
try{doSomething();}catch(Exceptionignore){}
事实上,这种代码大家一般只关心三个部分:1. 实行的动作;2. 和动作关联的异常;3. 异常的处置方法。想象中的伪代码可能是如此的:
captureIOExceptionfrom()-{}tohandleIOException
转换为Java代码,就是:
Catcher.capture(IllegalAccessException.class).from(()-{//dosomethingthrownewException(kdsfkj);}).to(Main::onFailed);//或Catcher.capture(IllegalAccessException.class,IOException.class).from(()-{//dosomethingthrownewException(kdsfkj);}).to(e-{//handleexception});Catcher的达成
publicclassCatcher{ListClass?classes=newlinkedList();privateActionaction;privateTextendsExceptionCatcher(ListClass?extendsTlist){classes.addAll(list);}@SafeVarargspublicstaticTextendsExceptionCatchercapture(Class?extendsT...classes){ListClass?extendsTlist=Arrays.asList(classes);returnnewCatcher(list);}publicCatcherfrom(Actionaction){this.action=action;returnthis;}publicvoidto(ConsumerExceptionexceptionConsumer){try{action.run();}catch(Exceptione){for(Class?mClass:classes){if(mClass.isInstance(e)){exceptionConsumer.accept(e);return;}}thrownewIllegalStateException(e);}}publicinterfaceAction{voidrun()throwsException;}}
注意:本文所展示的代码仅用于娱乐作用与功效,如有启发,纯属巧合,请不要用在实质生产环境






