Catch a generic exception in Java?

前端 未结 7 1158
不知归路
不知归路 2020-12-11 14:26

We use JUnit 3 at work and there is no ExpectedException annotation. I wanted to add a utility to our code to wrap this:

 try {
     someCode();         


        
7条回答
  •  北海茫月
    2020-12-11 15:10

    @FunctionalInterface
     public interface ThrowingConsumer {
          void accept(T t) throws E;
     }
    
    public static  Consumer errConsumerWrapper(ThrowingConsumer throwingConsumer,
                       Class exceptionClass, 
                       Consumer exceptionConsumer) {
                return i -> {
                    try {
                        throwingConsumer.accept(i);
                    } catch (Exception ex) {
                        try {
                            exceptionConsumer.accept(exceptionClass.cast(ex));
                        } catch (ClassCastException ccEx) {
                            throw new RuntimeException(ex);
                        }
                    }
                };
            }
    
    1. Usage example

      Stream.of("a").forEach(errConsumerWrapper(i -> Integer.parseInt(i), NumberFormatException.class, Throwable::printStackTrace));

提交回复
热议问题