How can I throw CHECKED exceptions from inside Java 8 streams?

前端 未结 18 1518
你的背包
你的背包 2020-11-22 06:59

How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?

In other words, I want to make code like this compile:

public List

        
18条回答
  •  有刺的猬
    2020-11-22 07:20

    I use this kind of wrapping exception:

    public class CheckedExceptionWrapper extends RuntimeException {
        ...
        public  CheckedExceptionWrapper rethrow() throws T {
            throw (T) getCause();
        }
    }
    

    It will require handling these exceptions statically:

    void method() throws IOException, ServletException {
        try { 
            list.stream().forEach(object -> {
                ...
                throw new CheckedExceptionWrapper(e);
                ...            
            });
        } catch (CheckedExceptionWrapper e){
            e.rethrow();
            e.rethrow();
        }
    }
    

    Try it online!

    Though exception will be anyway re-thrown during first rethrow() call (oh, Java generics...), this way allows to get a strict statical definition of possible exceptions (requires to declare them in throws). And no instanceof or something is needed.

提交回复
热议问题