Skip to lesson

Validate early and fail fast

Bad data is cheapest to catch at the door. A method that checks its inputs first and stops with a clear message turns a mysterious crash next week into an obvious error today, right next to its cause.

Fail fast: stop at the first bad value

Fail fast means checking inputs at the start and stopping with a clear exception as soon as something is wrong, instead of failing later in a confusing way.

Fail fast means checking input as soon as it arrives and throwing at once when it is wrong. The program stops right next to the real mistake, instead of carrying bad data around and breaking somewhere else later.

Example 1 · Late failure: the crash is far from the mistake

LateFailureDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Student {    String roll;    String name;
    Student(String roll, String name) {   // no checks: anything goes in        this.roll = roll;        this.name = name;    }}
public class LateFailureDemo {    static List<Student> saved = new ArrayList<>();
    static void save(Student s) {        saved.add(s);        System.out.println("Saved roll " + s.roll);    }
    static void printReport() {        for (Student s : saved) {            System.out.println(s.roll + " " + s.name.toUpperCase());        }    }
    public static void main(String[] args) {        save(new Student("101", "Ananya"));        save(new Student("102", null));        // the real mistake happens here        save(new Student("103", "Rohit"));        try {            printReport();                     // ...but the crash happens here        } catch (NullPointerException e) {            System.out.println("Crashed in printReport, far away from the bad save");        }    }}
Output
Saved roll 101
Saved roll 102
Saved roll 103
101 ANANYA
Crashed in printReport, far away from the bad save

What this code does

  • The null name is accepted without complaint. The program fails only when printReport calls toUpperCase() on it.
  • In a real app the save and the report may be days apart, and the stack trace points at the report, not at whoever passed null. The next example moves the check to the constructor.

A null name saved today may crash a report printed next week. The stack trace then points at the report code, and nobody knows which screen saved the bad record. A check at the moment of saving would have named the culprit straight away. The rule of thumb: every public method and constructor checks its arguments before doing any work.

Objects.requireNonNull with a message

Objects.requireNonNull(value, message) returns value when it is not null, and otherwise throws NullPointerException with your message. It is the standard one-line null check, often used straight in an assignment: this.name = Objects.requireNonNull(name, "name must not be null");.

Example 2 · requireNonNull at the door

RequireNonNullDemo.javaJava
import java.util.Objects;
class Student {    private final String roll;    private final String name;
    Student(String roll, String name) {        this.roll = Objects.requireNonNull(roll, "roll must not be null");        this.name = Objects.requireNonNull(name, () -> "name must not be null for roll " + roll);    }
    String roll() { return roll; }    String name() { return name; }}
public class RequireNonNullDemo {    public static void main(String[] args) {        Student a = new Student("101", "Ananya");        System.out.println("Created " + a.roll() + " " + a.name());
        try {            new Student("102", null);        } catch (NullPointerException e) {            System.out.println("Rejected: " + e.getMessage());        }        try {            new Student(null, "Rohit");        } catch (NullPointerException e) {            System.out.println("Rejected: " + e.getMessage());        }    }}
Output
Created 101 Ananya
Rejected: name must not be null for roll 102
Rejected: roll must not be null

What this code does

  • requireNonNull returns its argument, so the check and the assignment fit in one line. A null now fails inside the constructor, at the exact call that passed it.
  • The second check uses the Supplier form, so the message name must not be null for roll 102 is built only when the name really is null. main catches the exceptions only to show the messages.

A second form takes a Supplier<String>: requireNonNull(name, () -> "name missing for roll " + roll). The message is then built only when the check fails, which helps when building it costs some work. The exception is still a NullPointerException, but it is thrown at the door, with a message that names the field, rather than deep inside some later method.

IllegalArgumentException and IllegalStateException

IllegalArgumentException means "the value you passed is not allowed": marks of 120, a negative amount, a blank roll number. IllegalStateException means "the values are fine, but this object cannot do that right now": submitting an exam that was never started.

Example 3 · Bad argument versus wrong state

StateDemo.javaJava
class ExamSession {    private final String roll;    private boolean started;    private boolean submitted;    private int answered;
    ExamSession(String roll) {        this.roll = roll;    }
    void start() {        if (started) {            throw new IllegalStateException("exam already started for " + roll);        }        started = true;        System.out.println(roll + ": exam started");    }
    void answer(int questionNo) {        if (questionNo < 1 || questionNo > 50) {            throw new IllegalArgumentException("question must be 1 to 50, got " + questionNo);        }        if (!started || submitted) {            throw new IllegalStateException("cannot answer: exam not in progress");        }        answered++;    }
    void submit() {        if (!started || submitted) {            throw new IllegalStateException("cannot submit: exam not in progress");        }        submitted = true;        System.out.println(roll + ": submitted, answers: " + answered);    }}
public class StateDemo {    static void attempt(Runnable action) {        try {            action.run();        } catch (IllegalArgumentException | IllegalStateException e) {            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());        }    }
    public static void main(String[] args) {        ExamSession s = new ExamSession("101");        attempt(s::submit);        attempt(s::start);        attempt(() -> s.answer(7));        attempt(() -> s.answer(70));        attempt(s::start);        attempt(s::submit);        attempt(() -> s.answer(8));    }}
Output
IllegalStateException: cannot submit: exam not in progress
101: exam started
IllegalArgumentException: question must be 1 to 50, got 70
IllegalStateException: exam already started for 101
101: submitted, answers: 1
IllegalStateException: cannot answer: exam not in progress

What this code does

  • Question 70 is a bad value no matter when it is passed, so it is an IllegalArgumentException.
  • Submitting before starting, starting twice and answering after submitting use valid calls at the wrong time, so they are IllegalStateException. The argument check comes first, because a bad argument is wrong in every state.

Paying with a closed wallet is another state error. Both exceptions are unchecked, both are in java.lang, and every Java developer knows them. Use them for broken rules before you invent your own classes. The message should name the rule and the bad value: marks must be 0 to 100, got 120.

Guard clauses at the top of a method

A guard clause is an if at the start of a method that throws (or returns) when an input is bad. All checks come first; the real work follows, with no extra nesting.

Example 4 · Nested ifs versus guard clauses

GuardClauseDemo.javaJava
public class GuardClauseDemo {    // Before: the real work is buried inside nested ifs    static String bookNested(String name, int age, int seats) {        if (name != null && !name.isBlank()) {            if (age >= 5) {                if (seats >= 1 && seats <= 6) {                    return "Booked " + seats + " seats for " + name;                } else {                    throw new IllegalArgumentException("seats must be 1 to 6, got " + seats);                }            } else {                throw new IllegalArgumentException("age must be 5 or more, got " + age);            }        } else {            throw new IllegalArgumentException("name is required");        }    }
    // After: guard clauses first, then the happy path at the left margin    static String book(String name, int age, int seats) {        if (name == null || name.isBlank()) {            throw new IllegalArgumentException("name is required");        }        if (age < 5) {            throw new IllegalArgumentException("age must be 5 or more, got " + age);        }        if (seats < 1 || seats > 6) {            throw new IllegalArgumentException("seats must be 1 to 6, got " + seats);        }        return "Booked " + seats + " seats for " + name;    }
    public static void main(String[] args) {        System.out.println(bookNested("Meena", 34, 2));        System.out.println(book("Meena", 34, 2));
        String[] names = {" ", "Kabir", "Kabir"};        int[] ages = {30, 3, 30};        int[] seats = {1, 1, 9};        for (int i = 0; i < names.length; i++) {            try {                book(names[i], ages[i], seats[i]);            } catch (IllegalArgumentException e) {                System.out.println("Rejected: " + e.getMessage());            }        }    }}
Output
Booked 2 seats for Meena
Booked 2 seats for Meena
Rejected: name is required
Rejected: age must be 5 or more, got 3
Rejected: seats must be 1 to 6, got 9

What this code does

  • Both methods follow the same rules and give the same results. In bookNested each error message sits far below its check, and the booking line is three levels deep.
  • In book each guard clause is one rule with its message right under it. Once all guards pass, the last line can trust every input.

Without guard clauses, checks often grow into if inside if inside if, and the happy path ends up deep on the right with each error message far below its check. Guard clauses keep each check next to its message and make the list of rules easy to read. For index checks, Java 9 added Objects.checkIndex(index, length), which throws IndexOutOfBoundsException with a clear message when the index is outside 0 to length - 1.

Validation in record compact constructors

A compact constructor is a record constructor written without a parameter list: record MarkEntry(String roll, int marks) { MarkEntry { ... } }. Its code runs before the fields are set, so it is the natural place for checks.

Example 5 · A record that checks and cleans its own data

RecordValidationDemo.javaJava
import java.util.Objects;
record MarkEntry(String roll, String subject, int marks) {    MarkEntry {        Objects.requireNonNull(roll, "roll must not be null");        Objects.requireNonNull(subject, "subject must not be null");        if (marks < 0 || marks > 100) {            throw new IllegalArgumentException("marks must be 0 to 100, got " + marks);        }        subject = subject.strip().toUpperCase();   // stored in its clean form    }}
public class RecordValidationDemo {    public static void main(String[] args) {        MarkEntry ok = new MarkEntry("101", " dbms ", 88);        System.out.println(ok);
        try {            new MarkEntry("102", "OS", 120);        } catch (IllegalArgumentException e) {            System.out.println("Rejected: " + e.getMessage());        }        try {            new MarkEntry("103", null, 70);        } catch (NullPointerException e) {            System.out.println("Rejected: " + e.getMessage());        }    }}
Output
MarkEntry[roll=101, subject=DBMS, marks=88]
Rejected: marks must be 0 to 100, got 120
Rejected: subject must not be null

What this code does

  • The compact constructor MarkEntry { ... } runs on every new MarkEntry(...), before the fields are assigned, so an invalid entry can never be created.
  • Assigning subject = subject.strip().toUpperCase() changes the parameter, and Java then stores the cleaned value in the field, as the printed subject=DBMS shows.

Every new MarkEntry(...) passes through it, so no invalid record can ever exist. You can also clean values there by assigning to the parameter, for example subject = subject.strip();, and the cleaned value is what gets stored.

Validate once, where the object is created. Code that receives a MarkEntry can then trust it and skip the same checks.

Next step

Check your understanding

12 quick questions