Interface CheckedConsumer<T>
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
Variant of
Consumer that behaves like Consumer, but which allows checked Exception's to be thrown
from its accept(Object) method-
Method Summary
Modifier and TypeMethodDescriptionvoidThis method performs the operation that may fail with a CheckedExceptionstatic <T> Consumer<T>safe(CheckedConsumer<T> runnableThatCanFailWithACheckedException) Wraps aCheckedConsumer(basically a lambda with one argument that doesn't return any result and which throws a CheckedException) by returning a newConsumerinstance
The returnedConsumer.accept(Object)method delegates directly to theaccept(Object)and catches any thrown checkedException's and rethrows them as aCheckedExceptionRethrownException
Unless you provide a context-message (usingsafe(String, CheckedConsumer)then any caught checkedException's message also becomes theCheckedExceptionRethrownException's message.
AnyRuntimeException's thrown aren't caught and the calling code will receive the originalRuntimeExceptionthrown.
Usage example:
Let's say we have a method calledsomeOperationthat cannot change, but which accepts aConsumerwith the purpose of the calling theConsumer.accept(Object).static <T> Consumer<T>safe(String contextMessage, CheckedConsumer<T> runnableThatCanFailWithACheckedException) Wraps aCheckedConsumer(basically a lambda with one argument that doesn't return any result and which throws a CheckedException) by returning a newConsumerinstance
The returnedConsumer.accept(Object)method delegates directly to theaccept(Object)and catches any thrown checkedException's and rethrows them as aCheckedExceptionRethrownException
AnyRuntimeException's thrown aren't caught and the calling code will receive the originalRuntimeExceptionthrown.
Usage example:
Let's say we have a method calledsomeOperationthat cannot change, but which accepts aConsumerwith the purpose of the calling theConsumer.accept(Object).
-
Method Details
-
accept
This method performs the operation that may fail with a CheckedException- Parameters:
arg- the argument to the consumer- Throws:
Exception- this method can throw both checkedException's as well asRuntimeException's