Java 8 method reference unhandled exception

If you look at the Consumer<T> interface, the accept method (which is what your method reference would effectively be using) isn’t declared to throw any checked exceptions – therefore you can’t use a method reference which is declared to throw a checked exception. The enhanced for loop is okay, because there you’re always in a context where SomeException can be thrown.

You could potentially create a wrapper which converts the checked exception to an unchecked exception, and throw that. Alternatively, you could declare your own functional interface with an accept() method which does throw a checked exception (probably parameterizing the interface with that exception), and then write your own forEach method that takes that functional interface as an input.

Leave a Comment