Lambda expressions can handle exceptions internally using a try-catch block. However, this approach can lead to verbose code, especially for checked exceptions.
Example of Exception Handling in Lambda:
import java.util.function.Consumer;
public class ExceptionHandlingExample {
public static void main(String[] args) {
// Lambda with exception handling
Consumer<String> printLength = input -> {
try {
int length = input.length();
System.out.println("Length: " + length);
} catch (NullPointerException e) {
System.out.println("Input is null");
}
};
// Test with null input
printLength.accept(null); // Output: Input is null
}
}
Handling Checked Exceptions in Lambda:
For checked exceptions, you can define a functional interface that throws the specific exception, allowing lambda expressions to throw checked exceptions.
Example of Handling Checked Exceptions in Lambda:
@FunctionalInterface
interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}
public class CheckedLambdaExample {
public static void main(String[] args) {
CheckedFunction<String, Integer> stringToInt = s -> {
if (s == null) {
throw new IllegalArgumentException("Input is null");
}
return Integer.parseInt(s);
};
try {
int result = stringToInt.apply("123");
System.out.println("Result: " + result); // Output: Result: 123
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Using Functional Interfaces for Exception Handling:
You can create custom functional interfaces that handle specific exceptions, allowing lambda expressions to throw those exceptions.
Example of Using Functional Interfaces for Exception Handling:
In this example, ThrowingConsumer is a functional interface that allows a lambda expression to throw an exception. The lambda expression inside printLength.accept(null) throws an IllegalArgumentException, which is caught in the catch block.
By using custom functional interfaces or existing functional interfaces with specific exceptions, you can handle exceptions in lambda expressions effectively, making your code more concise and readable while ensuring proper error handling.