Skip to content
Permalink
Browse files

Exception Consumer

  • Loading branch information
Ahmed Baber Khan
Ahmed Baber Khan committed Mar 27, 2017
0 parents commit 5e62034fde4b46957cca1688be856dcebd61539d
Showing with 55 additions and 0 deletions.
  1. +25 −0 src/com/test/ExceptionConsumer.java
  2. +30 −0 src/com/test/Test.java
@@ -0,0 +1,25 @@
package com.test;

import java.util.function.Consumer;

@FunctionalInterface
public interface ExceptionConsumer<T, E extends Exception> {
void accept(T t) throws E;

static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(ExceptionConsumer<T, E> exceptionConsumer)
throws E {

return i -> {
try {
exceptionConsumer.accept(i);
} catch (Exception ex) {
throwCheckedUnchecked(ex);
}
};
}

@SuppressWarnings("unchecked")
static <X extends Throwable> void throwCheckedUnchecked(Throwable t) throws X {
throw (X) t;
}
}
@@ -0,0 +1,30 @@
package com.test;

import java.util.Arrays;
import java.util.List;

public class Test {

public static void main(String[] args) throws MyException {

List<Integer> integers = Arrays.asList(3, 9, 7, 0, 10, 20);
integers.forEach(ExceptionConsumer.handlingConsumerWrapper(i -> writeToFile(i)));

}

static void writeToFile(Integer integer) throws MyException {
throw new MyException();
}
}

class MyException extends Exception {

/**
*
*/
private static final long serialVersionUID = 1L;

public MyException() {
super();
}
}

0 comments on commit 5e62034

Please sign in to comment.
You can’t perform that action at this time.