Interface ThrowingConsumer<T>
- Type Parameters:
T- The type of the input to the operation.
- All Superinterfaces:
Consumer<T>
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
This interface extends the standard Java Consumer to allow the functional method
to throw checked exceptions. The default accept(Object) method wraps any checked exceptions in a
RuntimeException, making it compatible with standard Consumer usage while still allowing
the implementation to throw checked exceptions via acceptThrows(Object).
Features:
- Functional interface - can be used with lambda expressions and method references
- Exception support - allows checked exceptions to be thrown via
acceptThrows(Object) - Compatible with Consumer - implements
Consumer.accept(Object)by wrapping exceptions - Dual interface - can be used as both Consumer and ThrowingConsumer
Use Cases:
- Operations that may throw I/O exceptions (file writing, network operations)
- Validation operations that may throw validation exceptions
- Side-effect operations that may fail with checked exceptions
- Operations that need to propagate checked exceptions
Usage:
Exception Handling:
acceptThrows(Object)- Throws checked exceptions directlyaccept(Object)- Wraps checked exceptions inRuntimeException- Use
acceptThrowswhen you need to handle specific checked exceptions - Use
acceptwhen you want standard Consumer behavior
See Also:
ThrowingSupplier- Supplier that throws exceptionsThrowingFunction- Function that throws exceptions- juneau-commons Basics
-
Method Summary
Modifier and TypeMethodDescriptiondefault voidPerforms this operation on the given argument, wrapping any checked exceptions in aRuntimeException.voidacceptThrows(T t) Performs this operation on the given argument, potentially throwing a checked exception.
-
Method Details
-
accept
Performs this operation on the given argument, wrapping any checked exceptions in aRuntimeException.This is the default implementation that makes this interface compatible with
Consumer. It callsacceptThrows(Object)and wraps any checked exceptions.- Specified by:
acceptin interfaceConsumer<T>- Parameters:
t- The input argument.- Throws:
RuntimeException- ifacceptThrows(Object)throws a checked exception.
-
acceptThrows
Performs this operation on the given argument, potentially throwing a checked exception.This is the functional method that implementations must provide. It allows checked exceptions to be thrown directly, unlike the standard
Consumer.accept(Object)method.Example:
ThrowingConsumer<String>
validator = (value ) -> {if (value ==null ||value .isEmpty()) {throw new ValidationException("Value cannot be empty" ); } };try {validator .acceptThrows("" ); }catch (ValidationExceptione ) {// Handle checked exception }- Parameters:
t- The input argument.- Throws:
Exception- If an error occurs during operation execution.
-