Sub topic 14
Dealing with Checked Exceptions in Lambdas
Some Java methods can fail in ways the compiler makes you plan for. When you call one of these methods inside a lambda, you may hit a compile error that seems strange at first. This chapter shows why that happens and two simple ways to fix it.
Checked and Unchecked Exceptions
An exception is an object Java throws when something goes wrong.
A checked exception is one the compiler forces you to handle. You must either catch it with try/catch or declare it with throws on your method. URISyntaxException and IOException are checked exceptions.
An unchecked exception is one the compiler does not track. RuntimeException and its subclasses, such as IllegalArgumentException, are unchecked.
Why Lambdas Cause Trouble
A lambda's body becomes the body of the functional interface's single method. Look at Function:
R apply(T t);This method has no throws clause. That means the lambda body cannot throw a checked exception either. So this line does not compile:
Function<String, URI> toUri = s -> new URI(s); // error: unreported URISyntaxExceptionThe constructor new URI(String) throws the checked URISyntaxException. Function.apply gives that exception no way out.
Fix 1: Catch Inside the Lambda
Use a block body with try/catch. Then wrap the checked exception in an unchecked one.
import java.net.URI;
import java.net.URISyntaxException;
import java.util.function.Function;
public class TryInside {
public static void main(String[] args) {
Function<String, URI> toUri = s -> {
try {
return new URI(s);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
};
System.out.println(toUri.apply("https://example.com").getHost()); // example.com
}
}Passing e into new RuntimeException(e) keeps the original error as the cause. You can still read it later with getCause().
This works, but the short one-line lambda has become six lines.
Fix 2: Write a Reusable Wrapper
If you need this often, write the try/catch once. First, define your own functional interface whose method is allowed to throw. Then write a helper that turns it into a normal Function.
import java.net.URI;
import java.util.function.Function;
public class CheckedExceptions {
@FunctionalInterface
interface ThrowingFunction<T, R> {
R apply(T t) throws Exception;
}
static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f) {
return t -> {
try {
return f.apply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
public static void main(String[] args) {
// new URI(String) throws the checked URISyntaxException,
// so URI::new cannot be used directly as a Function<String, URI>.
Function<String, URI> toUri = unchecked(URI::new);
System.out.println(toUri.apply("https://example.com").getHost()); // example.com
}
}Here is how it works, step by step:
URI::newis assigned to aThrowingFunction. Itsapplydeclaresthrows Exception, so this compiles.uncheckedreturns a plainFunctionthat callsf.applyinsidetry/catch.- Any checked exception gets wrapped in a
RuntimeException.
Choosing a Fix
| Situation | Good choice |
|---|---|
| One lambda, used once | Catch inside the lambda |
| Many lambdas with the same problem | A wrapper like `unchecked` |
| Your own API, and callers should handle the error | A custom interface with `throws` |
Exercise
Why does Function<String, URI> f = s -> new URI(s); fail to compile, while Function<String, Integer> g = s -> Integer.parseInt(s); compiles fine?
Show answer
new URI(s) throws URISyntaxException, which is a checked exception, and Function.apply has no throws clause to let it out. Integer.parseInt throws NumberFormatException, which is unchecked, so the compiler does not require you to handle it.
Exercise
Write a Function<String, String> lambda that calls java.nio.file.Files.readString(java.nio.file.Path.of(s)), which throws IOException, and wraps any failure in a RuntimeException.
Show answer
Function<String, String> read = s -> { try { return Files.readString(Path.of(s)); } catch (IOException e) { throw new RuntimeException(e); } }; (You need to import java.io.IOException, java.nio.file.Files, and java.nio.file.Path. Files.readString requires Java 11 or later.)