JAVA FOUNDATIONS · JAVA 17
Java exception handling: recover from one invalid input
Catch NumberFormatException at an input boundary while allowing later valid records to be processed.
Forsk Coding School learning resources · Updated 2026-10-26
What you will learn
- Place a catch around the operation that can fail
- Catch the specific exception you can handle
- Preserve useful error information without hiding defects
Before you start: Loops, arrays and method calls.
Identify the boundary where outside data enters
Converting text to an integer can fail when the text is not a valid integer representation or is outside the int range. Integer.parseInt reports that failure with NumberFormatException. The sample reads three strings representing marks. One is deliberately invalid, so the program must decide what to do with that record instead of assuming every conversion succeeds.
The try block is inside the loop. That placement matters: a failed conversion transfers control to its catch, then the next loop iteration can continue. Placing the entire loop in one try would stop the loop body at the first exception and resume after the catch, skipping later items unless additional logic restarted processing.
Handle the failure you understand
The catch names NumberFormatException because the program knows how to handle invalid integer text: print an input-error message and continue. A broad catch of Exception can also hide unrelated defects that the caller cannot sensibly repair. Do not catch an exception merely to suppress its message and pretend that the requested operation succeeded.
A valid parse is only one step of validation. The integer 150 parses successfully but may be invalid as a mark. Check such domain rules separately after conversion. Likewise, returning zero for every parse failure makes an invalid entry indistinguishable from a real zero unless the result carries separate success information.
Choose the right scope for recovery
This example treats records independently, so continuing is appropriate. A transaction that must update several records atomically would need a different policy. Exception handling should follow the operation's contract. For resources such as files or database connections, learn try-with-resources so cleanup happens reliably when a resource supports AutoCloseable.
While debugging, preserve enough context to locate the failed operation. Avoid printing personal data or secrets in logs. In this demonstration the inputs are synthetic numbers and a short invalid word. A production UI can show a clear validation message while internal logging records a safe error category and relevant technical context.
Run the worked example
Save as Main.java. Run javac Main.java, then java Main.
public class Main {
public static void main(String[] args) {
String[] inputs = {"82", "oops", "40"};
for (String input : inputs) {
try {
int mark = Integer.parseInt(input);
System.out.println("Mark: " + mark);
} catch (NumberFormatException exception) {
System.out.println("Invalid integer");
}
}
}
}Expected result
Mark: 82
Invalid integer
Mark: 40- 82 converts successfully and is printed.
- oops transfers control to the specific catch block.
- The loop continues and 40 is still processed.
Common mistakes to check
- Successful parsing does not prove that a value meets domain rules.
- A catch around the whole loop has a different recovery scope.
- Do not silently turn invalid input into a believable valid result.
Try it yourself
Parse {"5", "x", "7"}, add only valid integers, and print the final sum. Ignore invalid records with a specific catch.
Give me a hint
Keep sum outside the loop and put parseInt inside a per-record try.
Compare with one working solution
public class Main {
public static void main(String[] args) {
int sum = 0;
for (String input : new String[]{"5", "x", "7"}) {
try {
sum += Integer.parseInt(input);
} catch (NumberFormatException exception) {
// This record is invalid; continue to the next input.
}
}
System.out.println(sum);
}
}Expected result
12Quick check
Choose an answer, then check the explanation. Your answer stays in this page and is not saved as a student record.
Keep learning
Explain the result in your own words, change one input and predict the new output. For additional structured assignments, explore the workbook sample before requesting the full pack.
Explore the practice workbookReference documentation
Use the official reference to check language details. The explanations, examples and exercises on this page are written for this learning resource.
