Sub topic 14
Dealing with Checked Exceptions in Lambdas
You can now write lambdas, use the interfaces in java.util.function, and define your own functional interfaces. Sooner or later you will try to call a method inside a lambda that throws a checked exception, and the compiler will refuse to compile your code. This chapter explains why that happens and walks through four ways to deal with it.
Checked and Unchecked Exceptions
An exception is an object Java throws when something goes wrong while a program runs. Java has two kinds:
- A checked exception is one the compiler makes you handle. You must either catch it with
try/catchor declare it withthrowsin the method signature. Examples areIOExceptionandURISyntaxException. - An unchecked exception is one the compiler does not track. It is any subclass of
RuntimeException, such asNumberFormatExceptionorIllegalArgumentException.
A throws clause is the part of a method signature that lists the checked exceptions the method may throw, for example URI make(String s) throws URISyntaxException.
Why the Compiler Complains
A lambda is the body of one abstract method. The lambda follows the rules of that method, including its throws clause. Here is the abstract method of Function:
R apply(T t);This method has no throws clause, so any lambda used as a Function may not throw a checked exception. The constructor new URI(String) throws the checked URISyntaxException, which means this line fails:
import java.net.URI;
import java.util.function.Function;
public class DoesNotCompile {
public static void main(String[] args) {
// Uncomment to see the error: "unreported exception URISyntaxException"
// Function<String, URI> toUri = s -> new URI(s);
System.out.println("See the commented line above.");
}
}The same rule applies to Predicate, Consumer, Supplier, and every other interface in java.util.function. None of them declare checked exceptions.
Option 1: Catch the Exception Inside the Lambda
The most direct fix is to use a block body and handle the exception right there. You can recover, or you can rethrow it as an unchecked exception.
import java.net.URI;
import java.net.URISyntaxException;
import java.util.function.Function;
public class TryInsideLambda {
public static void main(String[] args) {
Function<String, URI> toUri = s -> {
try {
return new URI(s);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Bad address: " + s, e);
}
};
System.out.println(toUri.apply("https://example.com").getHost()); // example.com
}
}Note the second argument e passed to IllegalArgumentException. It stores the original exception as the cause, so the real reason for the failure is kept and shows up in the stack trace.
This approach works everywhere and is easy to read. Its downside is length. A one-line lambda has become seven lines.
Option 2: A Functional Interface That Declares the Exception
If you write the method that receives the lambda, you can define your own functional interface whose method declares the checked exception. The caller's lambda can then throw it freely, and your method decides how to handle it.
import java.net.URI;
import java.net.URISyntaxException;
public class ThrowingInterface {
@FunctionalInterface
interface UriMaker {
URI make(String text) throws URISyntaxException;
}
static void printHost(UriMaker maker, String text) {
try {
System.out.println(maker.make(text).getHost());
} catch (URISyntaxException e) {
System.out.println("Could not read: " + text);
}
}
public static void main(String[] args) {
printHost(URI::new, "https://example.com"); // example.com
printHost(URI::new, "a b"); // Could not read: a b
}
}Here URI::new is allowed because make declares throws URISyntaxException. This option keeps the exception checked, so the compiler still makes someone handle it. The limit is that it only helps with your own methods. You cannot pass a UriMaker to List.replaceAll or Stream.map, because those expect the standard interfaces.
Option 3: A Reusable Wrapper
When you need a standard Function and have many throwing calls, write one helper that turns a "throwing function" into a normal Function. The helper does the try/catch once, so each lambda can stay short.
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
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 (RuntimeException e) {
throw e; // already unchecked: pass it on unchanged
} catch (Exception e) {
throw new RuntimeException(e); // checked: wrap it, keep the cause
}
};
}
public static void main(String[] args) {
Function<String, URI> toUri = unchecked(URI::new);
System.out.println(toUri.apply("https://example.com").getHost()); // example.com
List<String> inputs = Arrays.asList("https://a.org", "bad address");
try {
List<String> hosts = inputs.stream()
.map(toUri)
.map(URI::getHost)
.collect(Collectors.toList());
System.out.println(hosts);
} catch (RuntimeException e) {
System.out.println("Failed: " + e.getCause().getClass().getSimpleName());
}
// Prints: Failed: URISyntaxException
}
}The extra catch (RuntimeException e) { throw e; } matters. Without it, an unchecked exception such as NullPointerException would get wrapped inside a second RuntimeException, which makes it harder to find. Order matters too: Java checks catch blocks from top to bottom, so the narrower RuntimeException must come before Exception.
For file and network code, Java provides java.io.UncheckedIOException, made for wrapping an IOException. Using it tells readers exactly what kind of failure was wrapped.
Option 4: Turn Failure into a Value
Sometimes one bad input should not stop the whole job. You can catch the exception in a small helper method and return an Optional. An Optional is a box that holds either one value or nothing. The caller then keeps the good results and skips the bad ones.
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class SkipBadValues {
static Optional<URI> tryParse(String s) {
try {
return Optional.of(new URI(s));
} catch (URISyntaxException e) {
return Optional.empty();
}
}
public static void main(String[] args) {
List<String> inputs = Arrays.asList("https://a.org", "bad address", "https://b.net");
List<String> hosts = inputs.stream()
.map(SkipBadValues::tryParse)
.filter(Optional::isPresent)
.map(Optional::get)
.map(URI::getHost)
.collect(Collectors.toList());
System.out.println(hosts); // [a.org, b.net]
}
}Moving the try/catch into a named method also keeps the lambda part short, because a method reference replaces it.
Choosing an Approach
| Approach | Exception stays checked? | Works with standard interfaces? | Best when |
|---|---|---|---|
| `try`/`catch` in the lambda | No (or handled on the spot) | Yes | One or two throwing calls |
| Custom interface with `throws` | Yes | No | You own the method taking the lambda |
| `unchecked` wrapper | No | Yes | Many throwing calls; failure should stop the work |
| Return `Optional` | Handled | Yes | Bad inputs should be skipped, not fatal |
Common Mistakes
- Swallowing the exception. An empty
catchblock hides errors. At minimum, rethrow or log. - Dropping the cause.
throw new RuntimeException("failed")loses the original exception. Passeas the cause. - Double wrapping. Catching
Exceptionwithout first rethrowingRuntimeExceptionwraps exceptions that were already unchecked. - Catching in the wrong place. In a stream, the exception is thrown when the stream runs (at
collect), not where you built theFunction. Put yourtryaround the code that runs the stream.
Exercise
Why does Consumer<String> c = s -> Thread.sleep(100); fail to compile, while the same call works inside a custom interface whose method is void run(String s) throws InterruptedException?
Show answer
Thread.sleep throws the checked InterruptedException. Consumer.accept has no throws clause, so a lambda implementing it may not throw checked exceptions. The custom interface's method declares throws InterruptedException, so a lambda implementing that method is allowed to throw it.
Exercise
In the unchecked helper, what goes wrong if you remove the catch (RuntimeException e) { throw e; } block, and the wrapped function throws a NullPointerException?
Show answer
catch (Exception e) would catch the NullPointerException and wrap it in a new RuntimeException. Callers would see a plain RuntimeException and have to dig through getCause() to find the real problem, even though it was already unchecked and needed no wrapping.
Exercise
You read a list of file paths and want the lines of every file that exists, ignoring missing files. Which of the four approaches fits best, and why?
Show answer
Returning a value such as Optional (Option 4) fits best. A missing file is an expected case that should be skipped, not a failure that stops all the work. A helper that catches IOException and returns Optional.empty() lets the stream filter out the missing files and keep the rest.