Keep objects valid with checks
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)An object is valid when every field holds a value that makes sense: marks from 0 to 100, a name that is not empty, a price that is not negative. Setters and constructors keep it valid by checking each value before saving it.
What a valid object means
A valid object is one whose data follows the class's rules. For a Student: the name is not empty, and marks are 0 to 100. A rule that must be true for every object, all the time, is the heart of encapsulation.
If the rule is true when the object is created, and every method keeps it true, then no code anywhere can ever see a wrong object. That is the goal of this lesson.
Check first, then save
Validation means checking a value before you accept it. The setter is the right place: it is the only door to the private field.
public void setMarks(int marks) { if (marks < 0 || marks > 100) { // 1. check first throw new IllegalArgumentException("Marks must be 0 to 100"); } this.marks = marks; // 2. then save}Always put the check before the assignment. Then a refused value never reaches the field, and the object keeps its old, correct value. A check written after the assignment is too late.
Print or throw?
A setter can refuse a value in two ways: print a message and return, or throw an IllegalArgumentException, Java's built-in exception for "this argument is not allowed".
Example 1 · Print and ignore: the caller is not told
class Student { private int marks;
public void setMarks(int marks) { if (marks < 0 || marks > 100) { System.out.println("Invalid marks: " + marks); return; } this.marks = marks; }
public int getMarks() { return marks; }}
public class PrintDemo { public static void main(String[] args) { Student s = new Student(); s.setMarks(85); s.setMarks(120); System.out.println("Marks saved!"); System.out.println("Marks: " + s.getMarks()); }}Invalid marks: 120 Marks saved! Marks: 85
What this code does
- The check works:
120never reaches the field, so the marks stay85. - But
maincannot tell that the call failed, and wrongly printsMarks saved!.
Example 2 · Throw an exception and catch it
class Student { private int marks;
public void setMarks(int marks) { if (marks < 0 || marks > 100) { throw new IllegalArgumentException("Marks must be 0 to 100, got " + marks); } this.marks = marks; }
public int getMarks() { return marks; }}
public class ThrowDemo { public static void main(String[] args) { Student s = new Student(); s.setMarks(85); try { s.setMarks(120); System.out.println("Marks saved!"); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Marks: " + s.getMarks()); }}Error: Marks must be 0 to 100, got 120 Marks: 85
What this code does
throwstopssetMarksat once, so the assignment never runs.Marks saved!is skipped too.- The
catchblock gets the exception, ande.getMessage()gives back the text written in the setter.
Throwing is usually better. After a print, the caller goes on as if all is fine and may print "Marks saved" by mistake. A thrown exception stops the setter at once and travels back to the caller with its message, as in throw and throws (opens in a new tab).
The constructor is a door too
setMarks checks, yet new Student("Rohan", 120) still makes a wrong object, because the constructor writes the field directly. Every door into the object needs the rule.
Example 3 · A constructor that skips the check
class Student { private String name; private int marks;
public Student(String name, int marks) { this.name = name; this.marks = marks; // no check here }
public void setMarks(int marks) { if (marks < 0 || marks > 100) { throw new IllegalArgumentException("Marks must be 0 to 100"); } this.marks = marks; }
public void show() { System.out.println(name + ": " + marks); }}
public class BackDoorDemo { public static void main(String[] args) { Student r = new Student("Rohan", 120); r.show(); }}Rohan: 120
What this code does
- The setter checks, but the constructor writes the field directly. A wrong object is made with no error.
- Every door into the object needs the same rule.
Example 4 · The constructor calls the setter
class Student { private String name; private int marks;
public Student(String name, int marks) { this.name = name; setMarks(marks); }
public void setMarks(int marks) { if (marks < 0 || marks > 100) { throw new IllegalArgumentException("Invalid marks for " + name + ": " + marks); } this.marks = marks; }
public void show() { System.out.println(name + ": " + marks); }}
public class OnePlaceDemo { public static void main(String[] args) { try { Student a = new Student("Aarav", 78); a.show(); Student r = new Student("Rohan", 120); r.show(); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } }}Aarav: 78 Error: Invalid marks for Rohan: 120
What this code does
- The rule is written once, in
setMarks, and the constructor uses it.nameis set first, so the message can use it. - For Rohan,
newfails: no object is made, sor.show()never runs.
Do not copy the check: let the constructor call the setter, setMarks(marks);, so the rule is written once. If the setter throws inside the constructor, new fails: no object is made and the variable is never assigned.
Predict the output
Predict what the check lets through
Read the code and pick what it prints.
Round 1 of 4
A refused value must never reach the field. What does this print?
null.Catching the error in main
One bad form entry should not stop a whole booking loop. Wrap risky calls in try / catch (IllegalArgumentException e); e.getMessage() returns the text you gave the exception.
Example 5 · Nobody catches the exception
class Student { private int marks;
public void setMarks(int marks) { if (marks < 0 || marks > 100) { throw new IllegalArgumentException("Marks must be 0 to 100"); } this.marks = marks; }}
public class CrashDemo { public static void main(String[] args) { Student s = new Student(); s.setMarks(-5); System.out.println("Done"); }}Exception in thread "main" java.lang.IllegalArgumentException: Marks must be 0 to 100 at Student.setMarks(CrashDemo.java:6) at CrashDemo.main(CrashDemo.java:15)
What this code does
- There is no
try/catch, so the program stops andDoneis never printed. - The stack trace names the exception, the message, and the lines:
setMarkson line 6, called frommainon line 15.
Example 6 · Several rules and a loop of form entries
class Passenger { private String name; private int age;
public Passenger(String name, int age) { setName(name); setAge(age); }
public void setName(String name) { if (name == null || name.isBlank()) { throw new IllegalArgumentException("Name is empty"); } this.name = name; }
public void setAge(int age) { if (age < 1 || age > 120) { throw new IllegalArgumentException("Bad age for " + name + ": " + age); } this.age = age; }
public String getName() { return name; }}
public class FormDemo { public static void main(String[] args) { String[] names = {"Priya", "", "Arjun"}; int[] ages = {21, 30, 150}; for (int i = 0; i < names.length; i++) { try { Passenger p = new Passenger(names[i], ages[i]); System.out.println("Booked: " + p.getName()); } catch (IllegalArgumentException e) { System.out.println("Skipped: " + e.getMessage()); } } }}Booked: Priya Skipped: Name is empty Skipped: Bad age for Arjun: 150
What this code does
- Each field has its own setter with its own rule, and the constructor calls both.
isBlank()is true for an empty or all-space name. - The
trysits inside the loop, so one bad entry is skipped and the loop goes on with the next one.
Put the try inside the loop body: one bad value then skips only that round, and the loop goes on. If nobody catches the exception, the program stops and prints a stack trace: the error and the lines it passed through. try and catch (opens in a new tab) has the details.
Next step
Check your understanding
12 quick questions