Sub topic 5
Ignoring catch parameters and lambda parameters
This chapter covers the two places where Java forces you to name a variable you often never read: the parameter of a catch block and the parameters of a lambda expression. Since Java 22 you can write _ in both. It assumes you know these things:
- try, catch and multi-catch
- the functional interfaces in
java.util.function - the
Mapmethods that take lambdas
Earlier chapters showed _ for local variables and loop variables. The idea is the same here. The declaration is required by the syntax, but the value is not needed.
Why these two positions need `_`
A catch clause always declares a parameter, even when the handler only needs to know that the exception happened. A lambda must accept every parameter its functional interface defines, even when the body needs only some of them.
Before Java 22 you filled these slots with throwaway names such as e, ignored, k or unused. That causes three problems:
- A reader must scan the body to confirm the name is never used.
- Some linters and IDEs warn about unused variables, so people invent naming rules to silence them.
- A name like
esuggests the exception matters, which is misleading when it does not.
An unnamed variable states the intent in the declaration. The compiler enforces it: the variable cannot be read anywhere.
Unnamed catch parameters
Replace the parameter name with _ and keep the exception type:
public class Parsing {
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 catch clause still filters by type, so only NumberFormatException is handled. Other exceptions propagate as usual. Only the name is gone.
Multi-catch
_ also works with a multi-catch clause. The alternatives are still separated by |, and there is one _ for the whole clause:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Readable {
static boolean canRead(Path path) {
try {
Files.readString(path);
return true;
} catch (IOException | SecurityException _) {
return false;
}
}
public static void main(String[] args) {
System.out.println(canRead(Path.of("does-not-exist.txt")));
}
}Without a name, the compiler does not need a common supertype for the parameter. It only has to check that no alternative is a subclass of another, which is the same rule as for named multi-catch.
Handlers that react without reading the exception
Many correct handlers never need the exception object. The usual case is restoring the thread's interrupt flag:
public class Pause {
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException _) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
pause(10);
System.out.println("done");
}
}The handler does its work through Thread.currentThread(). The InterruptedException instance carries nothing it needs.
Do not swallow exceptions by accident
_ makes silent handlers easy to write, so be deliberate. Use it when the exception type alone tells you everything. That is true for NumberFormatException on user input and for InterruptedException when you restore the flag. Name the parameter when you need the message, the stack trace, or the cause for logging or rethrowing.
Rules for the unnamed catch parameter
- The body cannot refer to
_. Writing_.getMessage()is a compile-time error, because_is not a name that can be looked up. - The type is still required. There is no
catch (_)form. - You can use
_in severalcatchclauses of onetry, and in nested handlers. Each declaration is independent and none of them conflicts with another. - The variable is not in scope in any useful sense. It cannot shadow or clash with a local variable called
ein the same method.
Unnamed lambda parameters
A lambda parameter list can contain _ anywhere a name would go. This is most useful with interfaces that have more parameters than your code needs.
One ignored parameter
computeIfAbsent passes the key to its mapping function. Often the new value does not depend on it:
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)));
}
}A single _ without parentheses is allowed, just as x -> ... is. The output has the keys a and b. The HashMap iteration order is not specified, so the entries can appear in either order.
Ignoring some parameters, keeping others
With a two-parameter lambda you can mix named and unnamed parameters. Parentheses are required, as for any lambda with more than one parameter:
import java.util.Map;
import java.util.TreeMap;
public class Stock {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>();
stock.put("apple", 3);
stock.put("pear", 0);
stock.forEach((name, _) -> System.out.println("item: " + name));
stock.forEach((_, qty) -> System.out.println("qty: " + qty));
stock.replaceAll((_, qty) -> qty + 1);
System.out.println(stock);
}
}Here forEach takes a BiConsumer<String, Integer> and replaceAll takes a BiFunction<String, Integer, Integer>. The lambda still receives both arguments. The _ parameter just gives you no way to read one of them.
Ignoring all parameters
You can use _ more than once in the same parameter list. Unnamed variables never clash with each other, so (_, _) is legal:
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Constants {
public static void main(String[] args) {
BiFunction<String, Integer, String> label = (_, _) -> "fixed";
System.out.println(label.apply("x", 1));
String repeated = IntStream.range(0, 3)
.mapToObj(_ -> "ab")
.collect(Collectors.joining());
System.out.println(repeated);
}
}The output is fixed and then ababab. The second example shows a common pattern: IntStream.range supplies a counter only to repeat an action.
Explicit types
A lambda may declare parameter types. _ works with those too, with an explicit type or with var:
import java.util.function.BiFunction;
public class Typed {
public static void main(String[] args) {
BiFunction<String, Integer, String> a = (String _, Integer _) -> "typed";
BiFunction<String, Integer, String> b = (var _, var _) -> "var";
System.out.println(a.apply("x", 1) + " " + b.apply("y", 2));
}
}Java still requires one style per lambda. You cannot mix implicitly typed and explicitly typed parameters in one parameter list, and _ does not change that. (_, Integer n) is rejected, but (String _, Integer n) is accepted.
The lambda body cannot read `_`
As with catch parameters, you cannot refer to an unnamed lambda parameter in the body. If the body needs the value, give the parameter a real name. Also, _ does not change which functional interface the compiler picks. Overload resolution depends on the number and types of parameters, not on their names. If a call with a named lambda was ambiguous, the same call with _ is ambiguous too.
Choosing between a name and `_`
Summary of the rules
| Position | Example | Allowed with `_` | Notes | Column |
|---|---|---|---|---|
| Catch parameter | `catch (IOException _)` | Yes | Type is required | |
| Multi-catch parameter | `catch (A \ | B _)` | Yes | One `_` for the clause |
| Single lambda parameter | `_ -> 0` | Yes | No parentheses needed | |
| Several lambda parameters | `(_, _) -> 0` | Yes | Repeats do not clash | |
| Mixed lambda parameters | `(k, _) -> k` | Yes | All implicit or all explicit | |
| Reading the value | `_.toString()` | No | Compile-time error |
Versions and migration
Unnamed variables were a preview feature in Java 21 (JEP 443). They became final in Java 22 (JEP 456). On Java 21 you must compile and run with --enable-preview, and set --release 21 or --source 21. On Java 22 and later no flag is needed.
Before Java 9, _ was a legal identifier that produced a warning. In Java 9 through 20 it was an error. If your project must still build on those versions, keep named parameters. Migrating is mechanical: rename the unused parameter to _ only where the body never refers to it. The compiler will report any place where you were wrong.
Edge cases to remember
- Nested lambdas. Each lambda has its own parameter list. An outer
_is invisible to an inner lambda, so the inner lambda cannot use it either. - Same name in an enclosing scope. A named lambda parameter cannot reuse the name of a local in the enclosing method. An unnamed one has no name, so that conflict cannot happen.
- Method references.
_appears only in declarations. A method reference likeString::lengthhas no parameter list to change. - Method and constructor parameters.
void log(String _)is not allowed. Only the positions in the table above, plus the ones from the earlier chapters, accept_. A later chapter lists every restriction.
Exercises
Exercise
This method compiles on Java 22. Identify every unnamed variable and say what each lambda or catch clause receives but does not use. import java.util.Map; import java.util.TreeMap; public class Report { public static void main(String[] args) { Map<String, Integer> counts = new TreeMap<>(); counts.put("a", 1); try { counts.forEach((key, ) -> System.out.println(key)); counts.computeIfAbsent("b", -> Integer.parseInt("x")); } catch (NumberFormatException _) { System.out.println("bad number"); } } }
Show answer
There are three unnamed variables. The second parameter of the forEach lambda is the map value, which is passed in but not used. The parameter of the computeIfAbsent lambda is the key "b", which is not needed to compute the value. The catch parameter is the NumberFormatException object, which the handler does not read. The program prints a, then Integer.parseInt("x") throws, and the handler prints bad number.
Exercise
A teammate writes catch (Exception _) { } around a database call so that the build stops warning about an unused variable. What is wrong with this, and what would you write instead if the failure should be reported?
Show answer
The empty handler catches every Exception, including unexpected bugs, and discards it with no trace. _ only removes the name; it does not make swallowing the failure safe. If the failure should be reported, name the parameter and use it, for example catch (SQLException e) { log.error("query failed", e); throw new IllegalStateException(e); }. Catching a narrower type than Exception is also better.