Sub topic 5
Ignoring catch parameters and lambda parameters
This chapter assumes you know try/catch, multi-catch, lambda expressions, and the functional interfaces Function and BiConsumer. It also assumes you have seen the basic form of an unnamed variable, _. The code runs on Java 22 or later. On Java 21, add --enable-preview --source 21.
Catch parameters
Every catch clause must declare a parameter, even when the handler never reads it. Before Java 22 you had to invent a name such as e or ignored. Now you can write _:
public class SafeParse {
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException _) {
return fallback;
}
}
public static void main(String[] args) {
System.out.println(parseOrDefault("42", -1));
System.out.println(parseOrDefault("forty-two", -1));
}
}This prints 42 and then -1. The _ tells the reader, and the compiler, that the exception object is deliberately not used. The compiler also rejects any attempt to read it.
_ also works in a multi-catch. The alternatives still have to be unrelated types, because a multi-catch cannot list a class together with its subclass.
public class SafeDivide {
static int divide(String a, String b) {
try {
return Integer.parseInt(a) / Integer.parseInt(b);
} catch (NumberFormatException | ArithmeticException _) {
return 0;
}
}
public static void main(String[] args) {
System.out.println(divide("10", "2"));
System.out.println(divide("10", "0"));
System.out.println(divide("x", "2"));
}
}Lambda parameters
A lambda must accept the parameters its functional interface defines. Map.computeIfAbsent passes the key to its function, but a new empty list does not depend on the key. Write _ for the key:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Grouping {
static Map<String, List<Integer>> group(List<String> keys, List<Integer> values) {
Map<String, List<Integer>> groups = new HashMap<>();
for (int i = 0; i < keys.size(); i++) {
groups.computeIfAbsent(keys.get(i), _ -> new ArrayList<>())
.add(values.get(i));
}
return groups;
}
public static void main(String[] args) {
System.out.println(group(List.of("a", "b", "a"), List.of(1, 2, 3)));
}
}The output is {a=[1, 3], b=[2]}. Map iteration order is not guaranteed, so the entries may print in the other order.
When a lambda has several parameters, you can ignore any of them. The remaining ones keep their names:
import java.util.Map;
public class Scores {
public static void main(String[] args) {
Map<String, Integer> scores = Map.of("ana", 90);
scores.forEach((_, score) -> System.out.println("score " + score));
scores.forEach((name, _) -> System.out.println("player " + name));
}
}You can also ignore all of them with (_, _) -> .... A single unnamed parameter can omit the parentheses, as in _ -> .... Several _ in one parameter list do not clash, because none of them is a real name. If you write an explicit type, the parenthesized form is required: (String _) -> 0.
A common case is a callback whose argument you don't need:
import java.util.concurrent.CompletableFuture;
public class Recover {
public static void main(String[] args) {
int result = CompletableFuture
.supplyAsync(() -> Integer.parseInt("oops"))
.exceptionally(_ -> -1)
.join();
System.out.println(result);
}
}This prints -1. The exceptionally method passes the Throwable to its function, and this handler ignores it.
Decision guide
Common errors
| Mistake | Result |
|---|---|
| Reading `_` in the body, such as `System.out.println(_)` | Compile error, because `_` has no name to refer to |
| Using `_` as a method parameter name, `void f(int _)` | Compile error, because method parameters cannot be unnamed |
| Compiling with Java 8 or earlier source level and using `_` | Treated as an ordinary identifier, with a warning |
| Compiling at Java 9 to 21 source level and using `_` | Compile error, because it is a reserved keyword |
Exercise
Rewrite this code so that no unused name remains, and say which of the two parameters you can replace: map.forEach((key, value) -> System.out.println(value)); and catch (IOException e) { return null; }.
Show answer
Both can be replaced. The first becomes map.forEach((_, value) -> System.out.println(value));, because key is never read and value is. The second becomes catch (IOException _) { return null; }, because e is never read. Consider logging the failure instead of silently returning null.
Exercise
Is catch (IllegalArgumentException | NumberFormatException _) valid? Why or why not?
Show answer
No. NumberFormatException is a subclass of IllegalArgumentException, and a multi-catch cannot list types related by inheritance. Using _ does not change that rule. Catch only IllegalArgumentException instead.