Lesson Overview
Use exceptions, validation and recovery paths to handle errors without hiding real problems.
Portfolio focus: Add validation to a constructor.
Starter: think before typing
Before running this robustness example, find the line where the main idea becomes active. Write a prediction: what must already be true for that line to work, and what should be different after it runs? The checked run ends with `Enter a whole number.`; predict how the focus line helps produce that evidence.
Learning Objectives
- Distinguish expected validation failures from exceptional failures.
- Use try/catch with a clear recovery plan.
- Throw exceptions when an object cannot be valid.
- Avoid swallowing errors silently.
Learning Outcomes
- By the end of the lesson, you can distinguish expected validation failures from exceptional failures.
- By the end of the lesson, you can use try/catch with a clear recovery plan.
- By the end of the lesson, you can throw exceptions when an object cannot be valid.
- By the end of the lesson, you can avoid swallowing errors silently.
Why this idea exists
Exceptions exist because error handling tangled into normal logic can make programs unreadable and unreliable. Languages introduced structured exception mechanisms to separate unusual failure paths from ordinary flow.
Defensive programming recognises that the world outside a method is not always well behaved: input can be wrong, files can disappear, network calls can fail and objects can be constructed incorrectly.
At degree level, the key question is recovery. Catching an exception is only useful if the program can respond sensibly; otherwise it should fail clearly, preserve evidence and avoid corrupting state.
Deep dive
Mechanism in this example
The important mechanism is visible around `String input = "forty";`. Read it as a concrete move in the program, not as decorative syntax: identify what value, object, branch, call or boundary is being created at that point.
Design pressure
At degree level, the key question is recovery. Catching an exception is only useful if the program can respond sensibly; otherwise it should fail clearly, preserve evidence and avoid corrupting state.
Failure mode to watch
For Exceptions and Defensive Programming, deliberately disturb the assumption behind `String input = "forty";`: use an awkward value, missing input, wrong order of calls or boundary case. The useful question is how that disturbance exposes a weakness in the robustness design.
Extension step
Extend the example by doing this: Handle invalid numeric input. The point is to make one small change that forces you to revisit the concept, rather than adding unrelated features.
Portfolio standard
The portfolio note should not repeat the lesson wording. It should show the edited code, the run result, and your own explanation of this evidence: write one test for an exception path.
Lesson visual

Type this and run it
Create ExceptionsAndDefensiveProgrammingDemo.java, type the program, and run it before changing anything. This section is about reproducing the checked baseline.
public class ExceptionsAndDefensiveProgrammingDemo {
public static void main(String[] args) {
String input = "forty";
try {
int value = Integer.parseInt(input);
System.out.println(value);
} catch (NumberFormatException ex) {
System.out.println("Enter a whole number.");
}
}
}Build and run it with:
javac ExceptionsAndDefensiveProgrammingDemo.java && java ExceptionsAndDefensiveProgrammingDemoExpected baseline: Enter a whole number.
Run the code in your browser
Use the editor as an experiment surface. First run the checked version, then make one small change to the part of the program that demonstrates robustness and compare the new behaviour with the reference output.
Enter a whole number.Line-by-line explanation
Read the code as a sequence of responsibilities. The focus line for this lesson is String input = "forty";; the surrounding lines prepare it, use its result or make the behaviour observable.
public class ExceptionsAndDefensiveProgrammingDemo {This names the runnable class for the Exceptions and Defensive Programming example, giving the compiler and JVM one clear unit to build.
public static void main(String[] args) {This is the program entry point. In Exceptions and Defensive Programming, it keeps the demonstration of robustness in one traceable starting script.
String input = "forty";This introduces input as named state for Exceptions and Defensive Programming. Later lines can read, update, pass or print that specific value as evidence.
try {This try line, `try {`, marks the Exceptions and Defensive Programming boundary between ordinary work and failure or cleanup behaviour.
int value = Integer.parseInt(input);This introduces value as named state for Exceptions and Defensive Programming. Later lines can read, update, pass or print that specific value as evidence.
System.out.println(value);This prints value as the observable evidence for Exceptions and Defensive Programming. The output lets the learner check whether the robustness idea behaved as predicted.
} catch (NumberFormatException ex) {This try line, `} catch (NumberFormatException ex) {`, marks the Exceptions and Defensive Programming boundary between ordinary work and failure or cleanup behaviour.
System.out.println("Enter a whole number.");This prints "Enter a whole number." as the observable evidence for Exceptions and Defensive Programming. The output lets the learner check whether the robustness idea behaved as predicted.
}This closes the innermost Exceptions and Defensive Programming block, so the immediately preceding method, branch or loop has finished.
}This closes the outer Exceptions and Defensive Programming structure, returning the reader to the surrounding class or file.
}This closing brace number 3 completes another layer of the Exceptions and Defensive Programming source structure Java has been checking.
Worked example
From code to explanation
Problem: Use Exceptions and Defensive Programming to complete a small portfolio-quality step: Add validation to a constructor.
Method: Locate the line `String input = "forty";`, explain the exact role it plays, then decide what you would change to extend the example without changing the whole program.
Reveal worked answer
The checked run should produce `Enter a whole number.`. A strong answer links the result back to robustness: what was created, selected, stored, called or protected, and why that matters for the portfolio task.
Trace the program
Before: Before the key operation, identify the relevant value, object, branch or resource that the robustness concept depends on.
During: Trace `String input = "forty";` as the Exceptions and Defensive Programming example executes. Say whether that operation creates data, checks a condition, calls behaviour, stores information or crosses a boundary.
After: Compare the run with the expected evidence: `Enter a whole number.`.
Change: Now handle invalid numeric input, run again, and explain the smallest reason the behaviour changed.
Common misconception
A common mistake in exceptions and defensive programming is treating the example as a finished answer. For robustness, the important question is narrower: which operation carries the idea, what does it make possible, and what would break if you changed it carelessly?
Quick checks
1. In this Exceptions and Defensive Programming example, what is the best reason to focus on `String input = "forty";`?
2. Which evidence is strongest after you edit and rerun this example?
How to study this lesson
For Exceptions and Defensive Programming, predict how robustness changes the run before you press Run.
Use the first portfolio task as your main edit: Add validation to a constructor.
Use the second task as your variation: Handle invalid numeric input.
Finish with evidence, not a diary entry: Write one test for an exception path.
Portfolio Practice
- Add validation to a constructor.
- Handle invalid numeric input.
- Write one test for an exception path.
Final self-check
Can you explain the key operation?
Explain the line identified in the quick check in one or two sentences. Your answer should say what it does before the output Enter a whole number. appears.
Can you justify the portfolio evidence?
Your evidence should include the original run, one edited run, and a short note explaining how the edit affected robustness.
Study route
Practise robustness by predicting the Java example, typing it, running it in the browser, tracing the result and saving portfolio evidence.
Next, move into Recursion, Sorting and Searching and carry forward one improvement from this lesson into the next program.
