You'll need to do one of the following.

  • If it's your code, then define your own functional interface that declares the checked exception:

    @FunctionalInterface
    public interface CheckedFunction<T, R> {
       R apply(T t) throws IOException;
    }
    

    and use it:

    void foo (CheckedFunction f) { ... }
    
  • Otherwise, wrap Integer myMethod(String s) in a method that doesn't declare a checked exception:

    public Integer myWrappedMethod(String s) {
        try {
            return myMethod(s);
        }
        catch(IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    

    and then:

    Function<String, Integer> f = (String t) -> myWrappedMethod(t);
    

    or:

    Function<String, Integer> f =
        (String t) -> {
            try {
               return myMethod(t);
            }
            catch(IOException e) {
                throw new UncheckedIOException(e);
            }
        };
    
Answer from jason on Stack Overflow
Top answer
1 of 16
574

You'll need to do one of the following.

  • If it's your code, then define your own functional interface that declares the checked exception:

    @FunctionalInterface
    public interface CheckedFunction<T, R> {
       R apply(T t) throws IOException;
    }
    

    and use it:

    void foo (CheckedFunction f) { ... }
    
  • Otherwise, wrap Integer myMethod(String s) in a method that doesn't declare a checked exception:

    public Integer myWrappedMethod(String s) {
        try {
            return myMethod(s);
        }
        catch(IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    

    and then:

    Function<String, Integer> f = (String t) -> myWrappedMethod(t);
    

    or:

    Function<String, Integer> f =
        (String t) -> {
            try {
               return myMethod(t);
            }
            catch(IOException e) {
                throw new UncheckedIOException(e);
            }
        };
    
2 of 16
258

You can actually extend Consumer (and Function etc.) with a new interface that handles exceptions -- using Java 8's default methods!

Consider this interface (extends Consumer):

@FunctionalInterface
public interface ThrowingConsumer<T> extends Consumer<T> {

    @Override
    default void accept(final T elem) {
        try {
            acceptThrows(elem);
        } catch (final Exception e) {
            // Implement your own exception handling logic here..
            // For example:
            System.out.println("handling an exception...");
            // Or ...
            throw new RuntimeException(e);
        }
    }

    void acceptThrows(T elem) throws Exception;

}

Then, for example, if you have a list:

final List<String> list = Arrays.asList("A", "B", "C");

If you want to consume it (eg. with forEach) with some code that throws exceptions, you would traditionally have set up a try/catch block:

final Consumer<String> consumer = aps -> {
    try {
        // maybe some other code here...
        throw new Exception("asdas");
    } catch (final Exception ex) {
        System.out.println("handling an exception...");
    }
};
list.forEach(consumer);

But with this new interface, you can instantiate it with a lambda expression and the compiler will not complain:

final ThrowingConsumer<String> throwingConsumer = aps -> {
    // maybe some other code here...
    throw new Exception("asdas");
};
list.forEach(throwingConsumer);

Or even just cast it to be more succinct!:

list.forEach((ThrowingConsumer<String>) aps -> {
    // maybe some other code here...
    throw new Exception("asda");
});

Update

Looks like there's a very nice utility library part of Durian called Errors which can be used to solve this problem with a lot more flexibility. For example, in my implementation above I've explicitly defined the error handling policy (System.out... or throw RuntimeException), whereas Durian's Errors allow you to apply a policy on the fly via a large suite of utility methods. Thanks for sharing it, @NedTwigg!.

Sample usage:

list.forEach(Errors.rethrow().wrap(c -> somethingThatThrows(c)));
🌐
Coderanch
coderanch.com › t › 745110 › java › Throwing-exceptions-lambda-expression
Throwing exceptions from a lambda expression (Java in General forum at Coderanch)
RTFJD (the JavaDocs are your friends!) If you haven't read them in a long time, then RRTFJD (they might have changed!) ... Rob Spoor wrote: You'll need to catch the runtime exception and throw its cause - the original exception. That can be quite some work if there can be more than one exception type. Here's an example from my own IOException-supporting function library: https://robtimus.github.io/io-functions/. The call to unchecked is nearly identical to your wrapper method, it just throws UncheckedIOException instead of RuntimeException.
🌐
Baeldung
baeldung.com › home › java › exceptions in java lambda expressions
Exceptions in Java Lambda Expressions | Baeldung
August 27, 2025 - It’s because this method only handles lambda expressions for Functional Interface of type Consumer. We can write similar wrapper methods for other Functional Interfaces like Function, BiFunction, BiConsumer and so on. Let’s modify the example from the previous section and instead of printing to the console, let’s write to a file. static void writeToFile(Integer integer) throws IOException { // logic to write to file which throws IOException }
🌐
DZone
dzone.com › coding › java › mastering exception handling in java lambda expressions
Mastering Exception Handling in Java Lambda Expressions
March 12, 2024 - As the operate method in the MyFunction interface doesn't declare any checked exceptions, handling the exception directly within the lambda body is disallowed by the compiler. One workaround involves defining functional interfaces that explicitly ...
🌐
Java Mex
javamex.com › tutorials › lambdas › lambdas_exceptions.shtml
Java lambdas and exception handling
Because IOException is a common type of exception, a corresponding UnchckedIOException class also exists, and we could use that instead if it was important to distinguish between the error being an IOExeption vs some other type of exception. We could also define our own exception class: so long as it subclasses RuntimeException, we can throw it from a lambda expression and it will still be compatible with the Stream API.
🌐
Frankel
blog.frankel.ch › exceptions-lambdas
Exceptions in lambdas
October 16, 2022 - Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more. ... Lombok offers the @SneakyThrow annotation: it allows one to throw checked exceptions ...
🌐
Medium
medium.com › @sebastien_pel › java-exception-and-lambda-to-go-sneaky-or-not-part-1-d31d6911eeed
Java Exception and Lambda : To go sneaky or not? (Part 1) | by Sebastien Pelletier | Medium
September 12, 2018 - I invite you to read this excellent article by Grzegorz Piwowarek for a great explanation on how we can “trick” the java compiler to convert a checked exception into a unchecked exception, but basically we can take advantage of the fact that a generic type that extends Exception or Throwable is inferred as a RuntimeException, thus bypassing the compiler check, so we can write the following: In our example above, an actual SQLException will now be directly thrown from the this::queryDatabaseForCustomer method reference instead of a runtime exception wrapper around the root SQLException exception.
🌐
TutorialsPoint
tutorialspoint.com › what-are-the-rules-to-follow-while-using-exceptions-in-java-lambda-expressions
What are the rules to follow while using exceptions in java lambda expressions?
import java.io.*; interface ThrowException { void throwing(String message) throws IOException; } public class LambdaExceptionTest2 { public static void main(String[] args) throws Exception { ThrowException te = msg -> { // lambda expression throw new FileNotFoundException(msg); // FileNotFoundException is a sub-type of IOException }; te.throwing("Lambda Expression"); } }
Find elsewhere
🌐
Reddit
reddit.com › r/java › handling checked exceptions in java functional interfaces (lambdas)
r/java on Reddit: Handling Checked Exceptions in Java Functional Interfaces (Lambdas)
September 23, 2024 -

Hi everyone,

I'm working with Java's functional interfaces such as Function, Supplier, and Consumer, but I’ve encountered an issue when dealing with checked exceptions in lambda expressions. Since Java doesn't allow throwing checked exceptions from these functional interfaces directly, I'm finding it difficult to handle exceptions cleanly without wrapping everything in try-catch blocks, which clutters the code.

Does anyone have suggestions on how to handle checked exceptions in lambdas in a more elegant way?

🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › troubleshooting issues in lambda › troubleshoot execution issues in lambda
AWS Lambda function errors in Java
Lambda: Remote debugging with Visual ... Lambda runtime runs your function code, the event might be processed on an instance of the function that's been processing events for some time, or it might require a new instance to be initialized....
🌐
TutorialsPoint
tutorialspoint.com › how-to-handle-an-exception-using-lambda-expression-in-java
How to handle an exception using lambda expression in Java?\\n
interface Student { void studentData(String name) throws Exception; } public class LambdaExceptionTest { public static void main(String[] args) { // lamba expression Student student = name -> { System.out.println("The Student name is: " + name); throw new Exception(); }; try { student.studentData("Adithya"); } catch(Exception e) { } } }
🌐
DZone
dzone.com › coding › java › how to handle checked exceptions with lambda expression
How to Handle Checked Exceptions With Lambda Expression
November 7, 2018 - We can write a similar functional interface, which would use a checked exception. Let’s do that. @FunctionalInterface public interface ThrowingFunction<T, R, E extends Throwable> { R apply(T t) throws E; } This functional interface has three generic types, including one that extends a Throwable. Since Java 8, an interface can have static methods, let’s write one here.
🌐
W3Docs
w3docs.com › java
Java 8 Lambda function that throws exception?
parseInt = s -> Integer.parseInt(s); try { int number = parseInt.apply("123"); } catch (NumberFormatException e) { // handle exception } ... In this example, the ThrowingFunction interface is a functional interface that declares a NumberFormatException in its throws clause. The parseInt variable is a lambda expression that calls the Integer.parseInt() method, which can throw a NumberFormatException...
🌐
Codemia
codemia.io › knowledge-hub › path › java_8_lambda_function_that_throws_exception
Java 8 Lambda function that throws exception?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
4Comprehension
4comprehension.com › home › sneakily throwing exceptions in lambda expressions in java
Sneakily Throwing Exceptions in Lambda Expressions in Java - { 4Comprehension }
September 27, 2018 - Which simply means that every T in “<T extends Throwable>” is generously inferred to be a RuntimeException if an inference of a more concrete type is not possible. This was originally intended to e.g. solve the ambiguous problem of inferring checked exceptions types from empty lambda expression bodies.
Top answer
1 of 2
68

You are not allowed to throw checked exceptions because the accept(T t, U u) method in the java.util.function.BiConsumer<T, U> interface doesn't declare any exceptions in its throws clause. And, as you know, Map#forEach takes such a type.

public interface Map<K, V> {

    default void forEach(BiConsumer<? super K, ? super V> action) { ... }

}                        |
                         |
                         V
@FunctionalInterface
public interface BiConsumer<T, U> {

    void accept(T t, U u); // <-- does throw nothing

}

That is true when we are talking about checked exceptions. But you still can throw an unchecked exception (e.g. a java.lang.IllegalArgumentException):

new HashMap<String, String>()
    .forEach((a, b) -> { throw new IllegalArgumentException(); });
2 of 2
30

You can throw exceptions in lambdas.

A lambda is allowed to throw the same exceptions as the functional interface implemented by the lambda.

If the method of the functional interface doesn't have a throws clause, the lambda can't throw CheckedExceptions. (You still can throw RuntimeExceptions).


In your particular case, Map.forEach uses a BiConsumer as a parameter, BiConsumer is defined as:

public interface BiConsumer<T, U> {
    void accept(T t, U u);
}

A lambda expression for this functional interface can't throw CheckedExceptions.


The methods in the functional interfaces defined in java.util.function package don't throw exceptions, but you can use other functional interfaces or create your own to be able to throw exceptions, i.e. given this interface:

public interface MyFunctionalInterface<T> {
    void accept(T t) throws Exception;
}

The following code would be legal:

MyFunctionalInterface<String> f = (s)->throw new Exception("Exception thrown in lambda"); 
🌐
Bestprog
bestprog.net › en › 2020 › 12 › 16 › java-throwing-exceptions-in-lambda-expressions-examples
Java. Throwing exceptions in lambda expressions. Examples | BestProg
To implement the EmptyArrayException exception, develop a class of the same name; arrays must be the same length. If the arrays have different lengths, then throw a standard ArrayIndexOutOfBoundsException. The lambda expression must be passed to the method as a parameter.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Lambdas & Exceptions: A Guide for Java Developers - Java Code Geeks
March 30, 2024 - Error Handling Scope: Error handling within the lambda might be limited. Consider if broader error handling is needed at a higher level. For Java 8 and above, a more advanced approach involves utilizing functional interfaces that can declare checked exceptions. These specialized interfaces allow you to define the method signature with a throws clause, enabling lambdas to propagate checked exceptions.
🌐
Reddit
reddit.com › r/java › exceptions in java lambdas
r/java on Reddit: Exceptions in Java lambdas
October 16, 2022 - Only after answering those questions you can declare that your activity needs/does not need to handle the checked exception, and even then, the solution is to cast the method reference to a lambda interface that would handle the error: interface ThrowingFunction<T, R> extends Function<T, R> { default R apply (T argument) { try { return applyThrowing(argument) } catch (Throwable e) { // common handling return null; // should it return null?
🌐
DZone
dzone.com › coding › java › sneakily throwing exceptions in lambda expressions
Sneakily Throwing Exceptions in Lambda Expressions - Java
October 3, 2017 - Since it's possible to rethrow checked exceptions as unchecked, why not use this approach for minimizing the amount of boilerplate used when dealing with aching exceptions in lambda expressions' bodies? First, we'd need a functional interface that represents a function that throws an Exception: public interface ThrowingFunction<T, R> { R apply(T t) throws Exception; And now, we could write an adapter method for converting it to the java.util.function.Function instance: