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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How do you run parseInt Guarded Argument Parsing?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.