parseInt Guarded Argument Parsing

Parse CLI numbers defensively: wrap parseInt in try/catch, reject blanks and out-of-range ports, and return OptionalInt instead of leaking exceptions.

JavaCli Tooling

Code

snippet
import java.util.List;
import java.util.OptionalInt;

public class SafeArgParsing {

    // 空白、非法数字与越界端口统一返回 empty,调用方不需要接异常
    static OptionalInt parsePort(String raw) {
        if (raw == null || raw.isBlank()) {
            return OptionalInt.empty();
        }
        try {
            int value = Integer.parseInt(raw.trim());
            return value > 0 && value <= 65535 ? OptionalInt.of(value) : OptionalInt.empty();
        } catch (NumberFormatException badNumber) {
            return OptionalInt.empty();
        }
    }

    public static void main(String[] args) {
        for (String raw : List.of("8080", " 443 ", "abc", "", "-1", "99999")) {
            OptionalInt port = parsePort(raw);
            String rendered = port.isPresent() ? String.valueOf(port.getAsInt()) : "(rejected)";
            System.out.println("'" + raw.strip() + "' -> " + rendered);
        }
    }
}

How it works

Count the class SafeArgParsing and the functions parsePort and main as the entire surface area of parseInt Guarded Argument Parsing.

The file repeats itself only inside for (String raw : List.of("8080", " 443 ", "abc", "", "-1", "99999")).

Using it

The main signature reads static OptionalInt parsePort(String raw)

The entry point wires parsePort together — run it once and the whole demo flows.

Key statements

return value > 0 && value <= 65535 ? OptionalInt.of(value) : OptionalInt.empty();
return OptionalInt.empty();
OptionalInt port = parsePort(raw);

Interactive Tools for This Topic

FAQ

How do you run parseInt Guarded Argument Parsing?
Direct execution is enough; the script has no external requirements.