Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an Exception in a Consumer Java 8

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?

like image 859
OEH Avatar asked Mar 02 '23 17:03

OEH


2 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!");
        }
    });
}
like image 200
Sourav Jha Avatar answered Mar 11 '23 09:03

Sourav Jha


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();
}
like image 20
Jean-Baptiste Yunès Avatar answered Mar 11 '23 10:03

Jean-Baptiste Yunès