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