// generics/ThrowGenericException.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.import java.util.*;interface Processor<T, E extends Exception> {void process(List<T> resultCollector) throws E;}class ProcessRunner<T, E extends Exception>extends ArrayList<Processor<T, E>> {List<T> processAll() throws E {List<T> resultCollector = new ArrayList<>();for(Processor<T, E> processor : this)processor.process(resultCollector);return resultCollector;}}class Failure1 extends Exception {}class Processor1implements Processor<String, Failure1> {static int count = 3;@Overridepublic void process(List<String> resultCollector)throws Failure1 {if(count-- > 1)resultCollector.add("Hep!");elseresultCollector.add("Ho!");if(count < 0)throw new Failure1();}}class Failure2 extends Exception {}class Processor2implements Processor<Integer, Failure2> {static int count = 2;@Overridepublic void process(List<Integer> resultCollector)throws Failure2 {if(count-- == 0)resultCollector.add(47);else {resultCollector.add(11);}if(count < 0)throw new Failure2();}}public class ThrowGenericException {public static void main(String[] args) {ProcessRunner<String, Failure1> runner =new ProcessRunner<>();for(int i = 0; i < 3; i++)runner.add(new Processor1());try {System.out.println(runner.processAll());} catch(Failure1 e) {System.out.println(e);}ProcessRunner<Integer, Failure2> runner2 =new ProcessRunner<>();for(int i = 0; i < 3; i++)runner2.add(new Processor2());try {System.out.println(runner2.processAll());} catch(Failure2 e) {System.out.println(e);}}}/* Output:[Hep!, Hep!, Ho!]Failure2*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。