Skip to content
Advertisement

Exception handling with Consumer functions in Java 8

This code gives me a compile error on the line processBatch(batch, this::backupMetacard); The process batch method wraps the consumer in a try/catch block, but Java will not compile the call.

JavaScript

Advertisement

Answer

The problem is that in the following snippet, the method backupMetacard declares to throw the checked IOException.

JavaScript

As such, it does not comply anymore with the contract of the functional method of Consumer, which is apply and doesn’t declare to throw checked exceptions.

Wrap this into a try-catch, where you can throw an unchecked exception instead UncheckedIOException:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement