Before this lesson
Understand method return values, type conversion and collection operations.
What you will be able to do
Separate malformed input, range failures and programming defects.
Understand the mechanism
An external string is not automatically an integer. Trim it, parse the format, then validate the business range. "25" is well formed, while "999" can still be out of range.
NumberFormatException extends IllegalArgumentException. parseMinutes exposes both malformed and out-of-range inputs as invalid arguments; the caller reports each rejected row and continues.
Keep the try block around a single conversion. Catching Exception can disguise unrelated defects as user mistakes. This sample reports a fixed invalid message; a UI can distinguish causes more precisely.
Runnable example
Use JDK 21. Save Main.java in a separate practice directory, compile with javac -encoding UTF-8 Main.java, then run java Main. Each lesson is independent; do not combine multiple public Main classes.
public class Main {
static int parseMinutes(String raw) {
if (raw == null) throw new IllegalArgumentException("missing value");
int value = Integer.parseInt(raw.trim());
if (value < 0 || value > 240) throw new IllegalArgumentException("range");
return value;
}
public static void main(String[] args) {
for (String raw : new String[] {"25", " 0 ", "2.5", "-1", "999"}) {
try { System.out.println("ok=" + parseMinutes(raw)); }
catch (IllegalArgumentException e) { System.out.println("invalid"); }
}
}
}
Trace and verify
25 and 0 pass. 2.5 is malformed; -1 and 999 fail the range check, producing three invalid lines.
Common mistakes and boundaries
Blank input is not zero. Numbers outside int range also fail parsing. Silently defaulting every error to zero loses the distinction from genuine zero duration.
Practice challenge
Add empty string, null, 240 and 241 as test inputs.
Reference solution and reasoning
The first two are invalid, 240 gives ok=240 and 241 is invalid. The boundary includes 240, so use >240 rather than >=240.