HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaCritical

Java 8 Lambda function that throws exception?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
javafunctionexceptionthrowsthatlambda

Problem

I know how to create a reference to a method that has a String parameter and returns an int, it's:

Function


However, this doesn't work if the function throws an exception, say it's defined as:

Integer myMethod(String s) throws IOException


How would I define this reference?

Solution

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 {
   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 f = (String t) -> myWrappedMethod(t);


or:

Function f =
    (String t) -> {
        try {
           return myMethod(t);
        }
        catch(IOException e) {
            throw new UncheckedIOException(e);
        }
    };

Code Snippets

@FunctionalInterface
public interface CheckedFunction<T, R> {
   R apply(T t) throws IOException;
}
void foo (CheckedFunction f) { ... }
public Integer myWrappedMethod(String s) {
    try {
        return myMethod(s);
    }
    catch(IOException e) {
        throw new UncheckedIOException(e);
    }
}
Function<String, Integer> f = (String t) -> myWrappedMethod(t);
Function<String, Integer> f =
    (String t) -> {
        try {
           return myMethod(t);
        }
        catch(IOException e) {
            throw new UncheckedIOException(e);
        }
    };

Context

Stack Overflow Q#18198176, score: 574

Revisions (0)

No revisions yet.