// 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 { void process(List resultCollector) throws E; } class ProcessRunner extends ArrayList> { List processAll() throws E { List resultCollector = new ArrayList<>(); for(Processor processor : this) processor.process(resultCollector); return resultCollector; } } class Failure1 extends Exception {} class Processor1 implements Processor { static int count = 3; @Override public void process(List resultCollector) throws Failure1 { if(count-- > 1) resultCollector.add("Hep!"); else resultCollector.add("Ho!"); if(count < 0) throw new Failure1(); } } class Failure2 extends Exception {} class Processor2 implements Processor { static int count = 2; @Override public void process(List 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 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 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 */