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

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

    This answer is similar to 17 but avoiding wrapper exception definition:

    List test = new ArrayList();
            try {
                test.forEach(obj -> {
    
                    //let say some functionality throws an exception
                    try {
                        throw new IOException("test");
                    }
                    catch(Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            }
            catch (RuntimeException re) {
                if(re.getCause() instanceof IOException) {
                    //do your logic for catching checked
                }
                else 
                    throw re; // it might be that there is real runtime exception
            }
    

提交回复
热议问题