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

前端 未结 18 1841
你的背包
你的背包 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:43

    Probably, a better and more functional way is to wrap exceptions and propagate them further in the stream. Take a look at the Try type of Vavr for example.

    Example:

    interface CheckedFunction {
        O apply(I i) throws Exception; }
    
    static  Function unchecked(CheckedFunction f) {
        return i -> {
            try {
                return f.apply(i);
            } catch(Exception ex) {
    
                throw new RuntimeException(ex);
            }
        } }
    
    fileNamesToRead.map(unchecked(file -> Files.readAllLines(file)))
    

    OR

    @SuppressWarnings("unchecked")
    private static  T throwUnchecked(Exception e) throws E {
        throw (E) e;
    }
    
    static  Function unchecked(CheckedFunction f) {
        return arg -> {
            try {
                return f.apply(arg);
            } catch(Exception ex) {
                return throwUnchecked(ex);
            }
        };
    }
    

    2nd implementation avoids wrapping the exception in a RuntimeException. throwUnchecked works because almost always all generic exceptions are treated as unchecked in java.

提交回复
热议问题