Exception Handling and Assertions

Where control goes when something fails.

6 lessons · 19 past questions · 97 marks in the papers collected here

Open the interactive lessons →Exception Handling and Assertions past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. A throw leaves the line at once
  2. Your own types: checked or unchecked
  3. Catch it, note it, throw it on
  4. Keeping the first reason
  5. Assertions run in order
  6. Switching assertions on

1. A throw leaves the line at once

A failing line does not finish. Control jumps to someone who can take over.

which lines run, and which are skipped, when something is thrown

A vending machine runs three steps: main asks it to serve, serving asks it to drop a can, and dropping checks the coins. With one coin too few, the innermost step cannot do its job. It also does not know what to tell the customer. Who decides what happens next?

Think of a worker who meets a problem and passes it to the person who gave them the task, who passes it up again, until someone has instructions for it. The analogy stops here: in Java the workers who pass it on never finish their own task. Their remaining lines are dropped.

Why jump instead of continuing? The next line usually depends on the failed one: you cannot say "thank you" for a can that never fell. So Java refuses to run on. It builds an exception, an object that records what went wrong, and throws it: it removes unfinished calls from the stack, newest first, until it finds one waiting inside a try with a catch that fits. This removal is stack unwinding.

The shape

try { watched lines } catch (Type name) { handler }. If a watched line (or anything it calls) throws an object that is a Type, the handler runs with name pointing at that object. Then execution continues after the whole block. If nothing is thrown, the handler is skipped.

Worked example: One coin short

Problem.

What does the vending program print?

public class Main {
    static void drop(int coins) {
        System.out.println("check coins");
        if (coins < 2) {
            throw new IllegalStateException("need 2 coins");
        }
        System.out.println("can drops");
    }
    static void serve(int coins) {
        System.out.println("serve start");
        drop(coins);
        System.out.println("serve end");
    }
    public static void main(String[] args) {
        try {
            serve(1);
            System.out.println("thank you");
        } catch (IllegalStateException e) {
            System.out.println("refund: " + e.getMessage());
        }
        System.out.println("ready again");
    }
}

What is asked.

Every printed line, in order.

Idea.

Follow the calls down to the throw, then walk back up and skip everything that was unfinished.

  1. main enters its try and calls serve(1), which prints serve start.
  2. serve calls drop(1), which prints check coins.
  3. 1 < 2 is true, so drop throws. Its line can drops is skipped.
  4. drop has no handler, and serve has none: serve end is skipped.
  5. main has a matching catch. thank you is skipped, and the handler prints refund: need 2 coins.
  6. After the block, ready again prints.

Answer.

serve start, check coins, refund: need 2 coins, ready again

Common mistake.

Printing serve end or thank you after the handler, as if the skipped calls resumed.

What if

The vending program calls serve(1) inside a try whose handler names IllegalStateException.

  • The call becomes serve(2). Which lines print?
    It prints serve start, check coins, can drops, serve end, thank you, ready again.. Nothing is thrown, so no line is skipped and the handler is ignored.
  • The handler names ArithmeticException instead. What happens?
    It prints serve start and check coins, then the run ends with an uncaught IllegalStateException.. The thrown object is not an ArithmeticException, so no handler matches and ready again is never reached.
  • The try-catch is moved into serve, around the call drop(coins) only, and main has no try. Is serve end printed now?
    Yes. It prints serve start, check coins, refund: need 2 coins, serve end, thank you, ready again.. The exception stops in serve, so serve and main both finish normally.

A throw climbs down the stack

  1. drop throws. It has no try, so its remaining line, can drops, will never run.
  2. drop is removed. serve has no try either, so serve end is skipped too.
  3. main was inside a try. The rest of that block, thank you, is skipped and catch is chosen.
  4. The handler runs and prints refund: need 2 coins. The exception is now finished.
  5. Execution continues after the whole try-catch: ready again. It never jumps back into drop.

Worked example: A handler inside a loop

Problem.

The shelf has two slots. What does this print?

public class Main {
    public static void main(String[] args) {
        int[] shelf = {7, 9};
        int[] asked = {1, 5, 0};
        for (int slot : asked) {
            try {
                System.out.println("slot " + slot);
                System.out.println("holds " + shelf[slot]);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("no such slot");
            }
        }
        System.out.println("done");
    }
}

What is asked.

All printed lines.

Idea.

The try is inside the loop, so a failure ends only the current round.

  1. Round 1: slot 1, then holds 9.
  2. Round 2: slot 5 prints. Reading shelf[5] throws before the second line can print.
  3. The handler prints no such slot. The loop body is finished, so the loop moves on.
  4. Round 3: slot 0, then holds 7.
  5. The loop ends and done prints.

Answer.

slot 1, holds 9, slot 5, no such slot, slot 0, holds 7, done

Common mistake.

Stopping the whole loop at the first exception.

Where the try sits

Try inside the loop

for (int slot : asked) {
    try { read(slot); }
    catch (ArrayIndexOutOfBoundsException e) { }
}

Try around the loop

try {
    for (int slot : asked) { read(slot); }
}
catch (ArrayIndexOutOfBoundsException e) { }

The difference. The position of try compared with for.

Inside: one round is lost and the loop goes on. Outside: all remaining rounds are lost.

When this breaks

"The handler takes over" is true only when the type matches. A catch for an unrelated exception class is ignored, the object keeps travelling, and if it leaves main the program ends with an error report.

2. Your own types: checked or unchecked

An exception class is a normal class. Its parent decides how strict the compiler is.

how to define an exception class and what the compiler demands for it

A parcel locker must say which bay is full. The built-in exception classes know nothing about lockers or bays. How do you throw a problem with your own name and your own text, and how does the caller know it might happen?

Write a small class. It is like printing your own complaint form: the form's title is the class name, and the text you fill in is the message. The analogy stops here: this form must have an official parent, an existing exception class, or Java will not let you throw it.

Why a parent? catch matches by type, so your class must sit in the type family that throw and catch understand. The family is rooted at Throwable. Its two main branches are Error (serious trouble in the machine) and Exception (problems a program may handle). Under Exception sits RuntimeException, mostly programming mistakes.

Which branch decides the compiler's attitude

You extendKindMust the caller catch or declare it?
Exceptioncheckedyes
RuntimeExceptionuncheckedno
Erroruncheckedno
The catch-or-declare rule

If a method body can let a checked exception escape, the header must list it (or a parent of it) after throws. Otherwise the body must catch it. javac checks this for every method. throw (a statement) sends an object; throws (in a header) only announces.

Worked example: A full bay

Problem.

What does the locker program print?

class LockerFullException extends Exception {
    LockerFullException(int bay) {
        super("bay " + bay + " is full");
    }
}
public class Main {
    static void store(int bay, boolean full) throws LockerFullException {
        if (full) {
            throw new LockerFullException(bay);
        }
        System.out.println("stored in bay " + bay);
    }
    public static void main(String[] args) {
        try {
            store(3, false);
            store(4, true);
            store(5, false);
        } catch (LockerFullException e) {
            System.out.println(e.getMessage());
        }
    }
}

What is asked.

The output.

Idea.

The constructor builds the text; the handler reads it back with getMessage().

  1. store(3, false) skips the if and prints stored in bay 3.
  2. store(4, true) builds a LockerFullException. Its constructor passes bay 4 is full to super.
  3. The object leaves store. The call store(5, false) is skipped.
  4. The handler prints e.getMessage().

Answer.

stored in bay 3, then bay 4 is full

Common mistake.

Printing the class name, or running the third call after the handler.

What if

The locker program compiles. LockerFullException extends Exception.

  • The words throws LockerFullException are removed from the header of store. Does it compile?
    No: it is a compilation error at the throw line, and javac also rejects the catch in main.. A checked exception would escape a method that does not announce it. The handler in main names a checked class that can no longer arrive.
  • The class extends RuntimeException, and the throws words stay removed. Does it compile, and what prints?
    It compiles and prints the same two lines.. Unchecked exceptions need no announcement. At run time the throw travels in the same way.
  • The original class is kept, but main calls store(4, true); with no try and no throws. What happens?
    It is a compilation error at that call.. main is a method like any other: it must catch or declare.

One word in the class header

Checked

class FullException extends Exception { }
static void add() {
    throw new FullException();
}

Unchecked

class FullException extends RuntimeException { }
static void add() {
    throw new FullException();
}

The difference. Exception against RuntimeException.

The left method does not compile without throws FullException; the right one does.

Throwing from a constructor. A constructor may throw too. Then new does not produce a value: the assignment around it never happens.

Worked example: A refused badge

Problem.

The second name is blank. What does this print?

class BlankNameException extends RuntimeException {
    BlankNameException(String message) {
        super(message);
    }
}
class Badge {
    static int started = 0;
    final String name;
    Badge(String name) {
        started++;
        if (name.isEmpty()) {
            throw new BlankNameException("badge " + started + " has no name");
        }
        this.name = name;
    }
}
public class Main {
    public static void main(String[] args) {
        Badge last = null;
        for (String name : new String[] {"Mei", "", "Omar"}) {
            try {
                last = new Badge(name);
            } catch (BlankNameException e) {
                System.out.println(e.getMessage());
            }
            System.out.println(last.name + " " + Badge.started);
        }
    }
}

What is asked.

All lines.

Idea.

A constructor that throws never returns a reference, so last keeps its old value. Work done before the throw is not undone.

  1. Round 1: new Badge("Mei") raises started to 1 and returns, so last is that badge: Mei 1.
  2. Round 2: started becomes 2, then the blank name makes the constructor throw. The assignment to last never happens.
  3. The handler prints badge 2 has no name.
  4. The line after the try-catch still runs: last is Mei's badge, and started stayed 2, so it prints Mei 2.
  5. Round 3: new Badge("Omar") succeeds: Omar 3.

Answer.

Mei 1, badge 2 has no name, Mei 2, Omar 3

Common mistake.

Thinking last becomes null, or that the failed construction also undoes started++.

When this breaks

"Unchecked needs nothing" means nothing for the compiler. If no handler catches it, an unchecked exception still ends the program.

3. Catch it, note it, throw it on

A handler may do a little and then pass the problem further.

a handler that throws the same exception again

A ticket booth finds the show sold out. The booth must close its window, but it cannot decide what the customer is offered: that is the office's job. So the booth has to react and still let the office hear about the problem.

Like a shop assistant who writes a complaint in the log and then hands the same complaint to the manager. The paper is not copied and not rewritten. The analogy stops at one point: the assistant stops working on that task the moment the paper is handed on.

Why does the rest follow from what you know? A catch block is ordinary code. A throw inside it is an ordinary throw. By then control has left the try, so the handlers of that statement are no longer watching. The object goes to the callers.

Rethrow

Inside catch (T e) { ... throw e; } the method ends abruptly with e. If e may be checked, the method header must announce it with throws, exactly as for a new throw.

Worked example: The booth and the office

Problem.

What does the booth program print?

class SoldOutException extends Exception {
    SoldOutException(String message) {
        super(message);
    }
}
public class Main {
    static void sell(int left) throws SoldOutException {
        if (left == 0) {
            throw new SoldOutException("show is sold out");
        }
        System.out.println("ticket sold");
    }
    static void queue(int left) throws SoldOutException {
        try {
            sell(left);
            System.out.println("next person");
        } catch (SoldOutException e) {
            System.out.println("booth closes");
            throw e;
        }
    }
    public static void main(String[] args) {
        try {
            queue(4);
            queue(0);
            System.out.println("all served");
        } catch (SoldOutException e) {
            System.out.println("office: " + e.getMessage());
        }
    }
}

What is asked.

Four lines in order.

Idea.

One object, two handlers: the nearer one prints first, then passes the object on.

  1. queue(4) calls sell(4), which prints ticket sold; then next person prints.
  2. queue(0) calls sell(0), which throws. next person is skipped this time.
  3. The handler in queue prints booth closes and runs throw e;.
  4. The object leaves queue; all served is skipped.
  5. The handler in main prints office: show is sold out.

Answer.

ticket sold, next person, booth closes, office: show is sold out

Common mistake.

Printing the office line before the booth line.

What if

The booth program prints the booth line and then the office line.

  • The line throw e; is deleted. What prints?
    It prints ticket sold, next person, booth closes, all served.. The handler in queue finishes the problem, so main never learns of it.
  • throw e; stays, but throws SoldOutException is removed from the header of queue. Does it compile?
    No: it is a compilation error at throw e;, and javac also rejects the catch in main.. A checked exception would leave a method that does not declare it, and main waits for a checked class that no call announces.
  • The first call becomes queue(0) and the second queue(4). What prints?
    It prints booth closes, then office: show is sold out.. The first call throws, so the second call is never made.

Caught, noted, thrown again

  1. queue(4) already printed two lines. Now sell(0) throws a new SoldOutException.
  2. queue catches it, so next person is skipped. The handler prints booth closes.
  3. throw e; throws the same object again, from inside queue.
  4. queue is removed. main skips all served and enters its own catch.
  5. main prints office: show is sold out: the message never changed on the way.

Worked example: A second catch that never helps

Problem.

What does this print?

public class Main {
    static void ride() {
        try {
            throw new IllegalArgumentException("flat tyre");
        } catch (IllegalArgumentException e) {
            System.out.println("first handler");
            throw e;
        } catch (RuntimeException e) {
            System.out.println("second handler");
        }
        System.out.println("ride over");
    }
    public static void main(String[] args) {
        try {
            ride();
        } catch (RuntimeException e) {
            System.out.println("shop: " + e.getMessage());
        }
    }
}

What is asked.

The output.

Idea.

The two handlers belong to one try. After the first is chosen, the second is out of the game.

  1. The try throws an IllegalArgumentException.
  2. The first handler fits and prints first handler.
  3. throw e; leaves ride. The second handler is not consulted, even though its type fits.
  4. ride over is skipped. main catches the object and prints shop: flat tyre.

Answer.

first handler, then shop: flat tyre

Common mistake.

Printing second handler because RuntimeException also matches.

Swallow or pass on

The handler ends quietly

catch (SoldOutException e) {
    System.out.println("booth closes");
}

The handler rethrows

catch (SoldOutException e) {
    System.out.println("booth closes");
    throw e;
}

The difference. The line throw e;.

Without it the method carries on normally; with it the method ends with the exception and callers must deal with it.

When this breaks

"Two handlers, two lines" needs an outer handler that fits. If no caller catches the rethrown object, you see the inner line and then an uncaught exception.

4. Keeping the first reason

A new exception can carry the old one inside it.

putting one exception inside another with initCause and reading it with getCause

A printer has an empty tray. Deep inside, the code that pulls a sheet reports tray is empty. The code that called it deals in print jobs, so it wants to report job 7 failed. If it throws only the new message, the real reason is lost. How can it send both?

Put the old report in an envelope and write the new headline on the front. Whoever receives it can read the headline, then open the envelope. The analogy stops here: nothing is copied. The envelope holds a reference to the very same old object.

Why not just rethrow? Rethrowing keeps the low-level type, so every caller would need to know about trays. Throwing a new, higher-level exception hides that detail. Storing the old one as the cause keeps the detail available for whoever is debugging.

Two methods

outer.initCause(inner) stores inner as the cause of outer. outer.getCause() returns that reference, typed as Throwable. Every exception class inherits both from Throwable.

Worked example: Job and tray

Problem.

What does the printer program print?

class PrintJobException extends Exception {
    PrintJobException(String message) {
        super(message);
    }
}
public class Main {
    static void pull(int sheets) {
        if (sheets == 0) {
            throw new IllegalStateException("tray is empty");
        }
        System.out.println("sheet pulled");
    }
    static void print(int sheets) throws PrintJobException {
        try {
            pull(sheets);
        } catch (IllegalStateException low) {
            PrintJobException job = new PrintJobException("job 7 failed");
            job.initCause(low);
            throw job;
        }
    }
    public static void main(String[] args) {
        try {
            print(0);
        } catch (PrintJobException e) {
            System.out.println(e.getMessage());
            System.out.println(e.getCause().getMessage());
            System.out.println(e.getCause().getClass().getSimpleName());
        }
    }
}

What is asked.

Three lines.

Idea.

Follow the two objects: build, link, throw the outer one, then read each one.

  1. print(0) calls pull(0), which throws an IllegalStateException. sheet pulled never prints.
  2. print catches it as low, builds job, and calls job.initCause(low).
  3. throw job; sends the wrapper to main.
  4. e.getMessage() is the wrapper's text: job 7 failed.
  5. e.getCause() is low: its message is tray is empty and its class name is IllegalStateException.

Answer.

job 7 failed, tray is empty, IllegalStateException

Common mistake.

Printing the inner message first because it happened first.

What if

The printer program prints the job message, then the tray message, then the class name.

  • The line job.initCause(low); is deleted. What happens at the second println?
    It prints job 7 failed, then the run ends with a NullPointerException.. getCause() returns null, and calling getMessage() on null fails.
  • The second println becomes System.out.println(e.getCause()); and the third is deleted. What is the second line?
    It prints java.lang.IllegalStateException: tray is empty.. Printing an exception object shows its full class name and then its message.
  • The first two lines of the catch body are removed and throw job; becomes throw low;. Does the program still compile and reach the handler in main?
    It compiles, but the handler for PrintJobException does not match, so the run ends with an uncaught IllegalStateException.. The thrown type is the low-level one again.

A low failure wrapped in a high one

  1. pull(0) throws the low-level problem: tray is empty.
  2. print catches it and calls it low. Callers of print should hear about a print job, not a tray.
  3. A second object, job, is built. job.initCause(low) stores the first one inside it.
  4. throw job; sends the new object upward. low travels inside it.
  5. main catches the high-level type. A catch for IllegalStateException would not match it.
  6. getMessage() reads the outer text; getCause().getMessage() reads the inner one.

Worked example: The cause can be set once

Problem.

What does this print?

public class Main {
    public static void main(String[] args) {
        Exception root = new Exception("valve stuck");
        RuntimeException alarm = new RuntimeException("pump alarm", root);
        try {
            alarm.initCause(new Exception("power cut"));
        } catch (IllegalStateException refused) {
            System.out.println("cause is already set");
        }
        System.out.println(alarm.getCause().getMessage());
        System.out.println(root.getCause());
    }
}

What is asked.

Three lines.

Idea.

A cause given to the constructor counts as already set.

  1. alarm is built with root as its cause.
  2. alarm.initCause(...) is a second attempt, so it throws an IllegalStateException.
  3. The handler prints cause is already set.
  4. The stored cause is unchanged: valve stuck.
  5. root was never given a cause, so the last line is null.

Answer.

cause is already set, valve stuck, null

Common mistake.

Believing the later call replaces the cause.

Link later or link at birth

initCause

JobError job = new JobError("failed");
job.initCause(low);
throw job;

Constructor with a cause

throw new RuntimeException("failed", low);

The difference. Where the cause is handed over.

Both give the same message and cause. Use initCause when the class has no constructor that accepts a cause.

When this breaks

"getCause().getMessage() gives the inner text" needs a cause to exist. With none stored, getCause() is null and the chain of calls throws a NullPointerException.

5. Assertions run in order

An assert states something that must be true at that line.

what an assert statement does and which one fails first

An oven program computes heat from degrees and minutes. The author believes that both inputs are positive and that the heat stays under a limit. If one belief is wrong, the later results are nonsense. How can the program test its own beliefs while the author is developing it?

Think of checkpoints on a walking route: at each one a guard looks at one thing. If it is fine you walk on without noticing. If not, you are stopped there, and you never see the later checkpoints. The analogy stops at one point: the guards can all be sent home, which the next lesson shows.

Why stop immediately? A false belief means the program is already in a state its author did not plan for. Continuing would only move the failure away from its source. So the first false check throws an AssertionError, and that object unwinds the stack like any other.

Syntax

assert condition; or assert condition : detail;. When enabled and the condition is false, Java throws an AssertionError. The detail, if present, is calculated only then and becomes the message. javac needs no special option.

Worked example: Two bakes

Problem.

The program runs with java -ea Main, so assertions are on. What happens?

public class Main {
    static int bake(int degrees, int minutes) {
        assert degrees > 0 : "degrees must be positive";      // check 1
        assert minutes > 0 : "minutes must be positive";      // check 2
        int heat = degrees * minutes;
        assert heat < 10000 : "too much heat " + heat;        // check 3
        return heat;
    }
    public static void main(String[] args) {
        System.out.println(bake(180, 20));
        System.out.println(bake(200, 60));
        System.out.println("shelf clear");
    }
}

What is asked.

The output and the failing check.

Idea.

Walk through the calls in order and test each check when it is reached.

  1. bake(180, 20): checks 1 and 2 are true; heat is 3600 and check 3 is true. 3600 prints.
  2. bake(200, 60): checks 1 and 2 are true.
  3. heat is 12000, so heat < 10000 is false. Check 3 throws.
  4. The detail builds the message too much heat 12000.
  5. No handler exists, so nothing more prints.

Answer.

3600, then an AssertionError from check 3

Common mistake.

Printing 12000 or shelf clear after the failed check.

What if

With -ea, the oven program prints 3600 and fails at check 3.

  • The second call becomes bake(0, 60). Which check fails?
    Check 1 throws, after 3600 is printed.. 0 > 0 is false and it is the first check reached.
  • The second call becomes bake(200, 50). Is 10000 allowed?
    No: check 3 throws, because 10000 < 10000 is false.. The boundary value fails a strict <.
  • The program is run without -ea. What prints?
    It prints 3600, 12000, shelf clear.. All checks are skipped.

The first false assert ends the run (-ea)

  1. All three checks of bake(180, 20) are true, so they are silent. main prints 3600.
  2. In bake(200, 60), checks 1 and 2 pass and heat is 12000. Check 3 is false, so an AssertionError with its detail is thrown.
  3. bake never returns a value, so the second println in main cannot run.
  4. Nobody catches it. The program stops with the error; shelf clear is never printed.

Worked example: Check order and null

Problem.

With -ea, what happens in the badge program?

public class Main {
    static String badge(String code) {
        assert code.length() == 4 : "four characters";   // check 1
        assert code != null : "code missing";            // check 2
        return "badge " + code;
    }
    public static void main(String[] args) {
        System.out.println(badge("AB12"));
        System.out.println(badge(null));
    }
}

What is asked.

The output and the failure.

Idea.

A condition must be calculated before it can be judged. Calculating it may itself fail.

  1. badge("AB12"): the length is 4 and the text is not null. badge AB12 prints.
  2. badge(null): check 1 calls code.length() on null.
  3. That call throws a NullPointerException while the condition is being calculated.
  4. Check 2, written to catch exactly this, is never reached.

Answer.

badge AB12, then a NullPointerException

Common mistake.

Answering AssertionError with the text code missing.

Two orders

Length first

assert code.length() == 4;
assert code != null;

Null test first

assert code != null;
assert code.length() == 4;

The difference. Which line comes first.

For a null argument the left order throws NullPointerException; the right order throws AssertionError.

When this breaks

"The first false assertion is the answer" breaks when a condition cannot be calculated at all: a method call on null or a division of an int by zero throws its own exception first. An empty string is not null.

6. Switching assertions on

The same compiled program behaves differently under different run commands.

how the java command decides which classes check their assertions

A park has two classes: Gate checks ages and Ride checks heights, both with assert. While testing the ride you want only the ride's checks to complain. How can you choose without editing the code?

Each class has its own light switch for assertions, and the java command flips the switches before the program starts. The analogy stops here: you cannot flip them while the lights are in use, only on the command line (or through rarely used loader calls).

Why off by default? Assertions are a development tool. A finished program should not pay for the checks, and should not depend on them. That is also why a check that is off does nothing: its condition is not calculated.

What the command enables

CommandClasses with checks on
java Mainnone
java -ea Mainall your classes
java -ea:Ride MainRide only
java -ea -da:Gate Mainall your classes except Gate

Worked example: Only the ride

Problem.

What happens with java -ea:Ride Main?

class Gate {
    static boolean admit(int age) {
        assert age >= 12 : "gate: too young";
        return true;
    }
}
class Ride {
    static boolean board(int height) {
        assert height >= 120 : "ride: too short";
        return true;
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("ride " + Ride.board(150));
        System.out.println("gate " + Gate.admit(10));
        System.out.println("ride " + Ride.board(100));
        System.out.println("enjoy");
    }
}

What is asked.

Output and failure.

Idea.

Mark each class on or off first, then trace.

  1. Only Ride is on. Gate and Main are off.
  2. Ride.board(150) runs its check, which is true, so it silently returns: ride true prints.
  3. Gate.admit(10) skips its false check and returns true: gate true prints.
  4. Ride.board(100) runs its check: 100 >= 120 is false.
  5. An AssertionError with message ride: too short is thrown. enjoy never prints.

Answer.

ride true, gate true, then an AssertionError from Ride

Common mistake.

Failing at the gate, as if one named class switched on all of them.

What if

With only Ride on, the park program prints ride true and gate true, then fails in Ride.

  • The command is plain java Main. What prints?
    It prints ride true, gate true, ride true, enjoy.. No class has its checks on.
  • The command is java -ea Main. Where does it stop, and what was printed?
    It prints ride true, then throws in Gate.. Both classes check now: height 150 passes, and age 10 fails.
  • The command is java -ea:Main Main. What prints?
    It prints ride true, gate true, ride true, enjoy.. Main is switched on, but it contains no assertion.

Worked example: A check with a side effect

Problem.

How many reads are reported, with java Main and with java -ea Main?

public class Main {
    static int reads = 0;
    static boolean sensorOk() {
        reads++;
        return true;
    }
    public static void main(String[] args) {
        assert sensorOk() : "sensor failed";
        System.out.println("reads " + reads);
    }
}

What is asked.

The line printed in each run.

Idea.

A disabled assertion does not even call the method in its condition.

  1. Without -ea the whole statement is skipped, so sensorOk() is never called: reads 0.
  2. With -ea the condition is calculated: sensorOk() adds 1 and returns true.
  3. The check passes silently, and the line is reads 1.

Answer.

reads 0 without the switch, reads 1 with it

Common mistake.

Calling the method but only suppressing the error.

All or one

Every class

java -ea Main

One class

java -ea:Ride Main

The difference. The text :Ride.

-ea alone enables all your classes; -ea:Name enables Name and leaves the others off.

When this breaks

"The check protects the input" is false in a normal run: with assertions off, bad values pass straight through. Real input checking uses if and throw.

Practise this topic →

Weeks covering this topic

Other Java topics