Multi Catch Exception Types

One multi-catch clause handles NumberFormatException and DateTimeParseException together; the types must be unrelated or the compiler rejects it.

JavaResilience

Code

snippet
import java.time.LocalDate;
import java.time.format.DateTimeParseException;

public class ConfigParser {

    static int parseWorkers(String raw) {
        return Integer.parseInt(raw.trim());
    }

    static LocalDate parseDeadline(String raw) {
        return LocalDate.parse(raw);
    }

    public static void main(String[] args) {
        String[][] settings = {
            {"workers", "not-a-number"},
            {"deadline", "2026-13-40"},
        };
        for (String[] setting : settings) {
            try {
                if (setting[0].equals("workers")) {
                    parseWorkers(setting[1]);
                } else {
                    parseDeadline(setting[1]);
                }
            } catch (NumberFormatException | DateTimeParseException e) {
                // multi-catch:两个 exception types 不能有继承关系,否则编译拒绝;
                // catch 参数隐式 final,不能在块内重新赋值
                System.out.println(setting[0] + " rejected: " + e.getClass().getSimpleName());
            }
        }
    }
}

How it works

The moving parts are the class ConfigParser and the functions parseWorkers, parseDeadline and main.

Iteration happens inside for (String[] setting : settings) — everything outside it runs once.

What to watch for

  • The toolchain alone is enough — no dependency resolution happens.

Using it

Signature: static int parseWorkers(String raw)

main calls 2 helpers in sequence: parseWorkers and parseDeadline.

The key statements that remain

return Integer.parseInt(raw.trim());
return LocalDate.parse(raw);

Interactive Tools for This Topic

FAQ

How do you run Multi Catch Exception Types?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.