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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With