How to throw an Exception in a Consumer Java 8

OEH :

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?

Sourav Jha :

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!");
        }
    });
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345925&siteId=1