How to throw an Exception in a Consumer Java 8

Viewed 1659

Is there any way to throw an Exception while using a consumer in java 8?

For example:

    private void fooMethod(List<String> list) throws Exception {

    list.forEach(element->{
        if(element.equals("a")) {
            throw new Exception("error!");
        }
    });

}

This gives me a compiler error saying: Unhandled exception type Exception

What is the correct way to throw an exception in this case?

3 Answers

Since Exception and its subclass (other than RuntimeException) are checked Exception and in lambda, you can't throw checked exception. Hence you should use RuntimeException:

private void fooMethod(List<String> list) throws Exception {
    list.forEach(element->{
        if(element.equals("a")) {
            throw new RuntimException("error!");
        }
    });
}

Streams and related classes are not designed to use checked exceptions. But any RuntimeException can be thrown at any point in code, thus the trick is to throw a runtime whose cause (exception chaining) is the appropriate checked exception :

private void fooMethod(List<String> list) throws Exception {   
    list.forEach(element->{
        if(element.equals("a")) {
            throw new Runtime(new Exception("error!"));
        }
    });  
}

Then in the catching code you just have to get the original checked exception encapsulated :

try {
    fooMethod(someList);
} catch(Throwable e) {
    Exception ex = e.getCause();
}

You can do it with apache commons-lang3 library.

https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/function/Failable.html

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

You can write:

import org.apache.commons.lang3.function.Failable;

private void fooMethod(List<String> list) throws Exception {
    list.forEach(Failable.asConsumer(element->{
        if(element.equals("a")) {
            throw new Exception("error!");
        }
    }));
}
Related