Where control goes when something fails.
Open the interactive lessons →Exception Handling and Assertions past questions
Contents
- A throw leaves the line at once
- Your own types: checked or unchecked
- Catch it, note it, throw it on
- Keeping the first reason
- Assertions run in order
- 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.
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.
mainenters itstryand callsserve(1), which printsserve start.servecallsdrop(1), which printscheck coins.1 < 2is true, sodropthrows. Its linecan dropsis skipped.drophas no handler, andservehas none:serve endis skipped.mainhas a matchingcatch.thank youis skipped, and the handler printsrefund: need 2 coins.- After the block,
ready againprints.
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.
The vending program calls serve(1) inside a try whose handler names IllegalStateException.
- The call becomes
serve(2). Which lines print?
It printsserve 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
ArithmeticExceptioninstead. What happens?
It printsserve startandcheck coins, then the run ends with an uncaughtIllegalStateException.. The thrown object is not anArithmeticException, so no handler matches andready againis never reached. - The
try-catchis moved intoserve, around the calldrop(coins)only, andmainhas notry. Isserve endprinted now?
Yes. It printsserve start,check coins,refund: need 2 coins,serve end,thank you,ready again.. The exception stops inserve, soserveandmainboth finish normally.
A throw climbs down the stack
dropthrows. It has notry, so its remaining line,can drops, will never run.dropis removed.servehas notryeither, soserve endis skipped too.mainwas inside atry. The rest of that block,thank you, is skipped andcatchis chosen.- The handler runs and prints
refund: need 2 coins. The exception is now finished. - Execution continues after the whole
try-catch:ready again. It never jumps back intodrop.
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.
- Round 1:
slot 1, thenholds 9. - Round 2:
slot 5prints. Readingshelf[5]throws before the second line can print. - The handler prints
no such slot. The loop body is finished, so the loop moves on. - Round 3:
slot 0, thenholds 7. - The loop ends and
doneprints.
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.
"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 extend | Kind | Must the caller catch or declare it? |
|---|---|---|
Exception | checked | yes |
RuntimeException | unchecked | no |
Error | unchecked | no |
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().
store(3, false)skips theifand printsstored in bay 3.store(4, true)builds aLockerFullException. Its constructor passesbay 4 is fulltosuper.- The object leaves
store. The callstore(5, false)is skipped. - 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.
The locker program compiles. LockerFullException extends Exception.
- The words
throws LockerFullExceptionare removed from the header ofstore. Does it compile?
No: it is a compilation error at thethrowline, andjavacalso rejects thecatchinmain.. A checked exception would escape a method that does not announce it. The handler inmainnames a checked class that can no longer arrive. - The class extends
RuntimeException, and thethrowswords 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
maincallsstore(4, true);with notryand nothrows. What happens?
It is a compilation error at that call..mainis 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.
- Round 1:
new Badge("Mei")raisesstartedto 1 and returns, solastis that badge:Mei 1. - Round 2:
startedbecomes 2, then the blank name makes the constructor throw. The assignment tolastnever happens. - The handler prints
badge 2 has no name. - The line after the
try-catchstill runs:lastis Mei's badge, andstartedstayed 2, so it printsMei 2. - 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++.
"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.
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.
queue(4)callssell(4), which printsticket sold; thennext personprints.queue(0)callssell(0), which throws.next personis skipped this time.- The handler in
queueprintsbooth closesand runsthrow e;. - The object leaves
queue;all servedis skipped. - The handler in
mainprintsoffice: 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.
The booth program prints the booth line and then the office line.
- The line
throw e;is deleted. What prints?
It printsticket sold,next person,booth closes,all served.. The handler inqueuefinishes the problem, somainnever learns of it. throw e;stays, butthrows SoldOutExceptionis removed from the header ofqueue. Does it compile?
No: it is a compilation error atthrow e;, andjavacalso rejects thecatchinmain.. A checked exception would leave a method that does not declare it, andmainwaits for a checked class that no call announces.- The first call becomes
queue(0)and the secondqueue(4). What prints?
It printsbooth closes, thenoffice: show is sold out.. The first call throws, so the second call is never made.
Caught, noted, thrown again
queue(4)already printed two lines. Nowsell(0)throws a newSoldOutException.queuecatches it, sonext personis skipped. The handler printsbooth closes.throw e;throws the same object again, from insidequeue.queueis removed.mainskipsall servedand enters its owncatch.mainprintsoffice: 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.
- The
trythrows anIllegalArgumentException. - The first handler fits and prints
first handler. throw e;leavesride. The second handler is not consulted, even though its type fits.ride overis skipped.maincatches the object and printsshop: 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.
"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.
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.
print(0)callspull(0), which throws anIllegalStateException.sheet pullednever prints.printcatches it aslow, buildsjob, and callsjob.initCause(low).throw job;sends the wrapper tomain.e.getMessage()is the wrapper's text:job 7 failed.e.getCause()islow: its message istray is emptyand its class name isIllegalStateException.
Answer.
job 7 failed, tray is empty, IllegalStateException
Common mistake.
Printing the inner message first because it happened first.
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 secondprintln?
It printsjob 7 failed, then the run ends with aNullPointerException..getCause()returnsnull, and callinggetMessage()onnullfails. - The second
printlnbecomesSystem.out.println(e.getCause());and the third is deleted. What is the second line?
It printsjava.lang.IllegalStateException: tray is empty.. Printing an exception object shows its full class name and then its message. - The first two lines of the
catchbody are removed andthrow job;becomesthrow low;. Does the program still compile and reach the handler inmain?
It compiles, but the handler forPrintJobExceptiondoes not match, so the run ends with an uncaughtIllegalStateException.. The thrown type is the low-level one again.
A low failure wrapped in a high one
pull(0)throws the low-level problem:tray is empty.printcatches it and calls itlow. Callers ofprintshould hear about a print job, not a tray.- A second object,
job, is built.job.initCause(low)stores the first one inside it. throw job;sends the new object upward.lowtravels inside it.maincatches the high-level type. AcatchforIllegalStateExceptionwould not match it.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.
alarmis built withrootas its cause.alarm.initCause(...)is a second attempt, so it throws anIllegalStateException.- The handler prints
cause is already set. - The stored cause is unchanged:
valve stuck. rootwas never given a cause, so the last line isnull.
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.
"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.
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.
bake(180, 20): checks 1 and 2 are true;heatis 3600 and check 3 is true.3600prints.bake(200, 60): checks 1 and 2 are true.heatis 12000, soheat < 10000is false. Check 3 throws.- The detail builds the message
too much heat 12000. - 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.
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, after3600is printed..0 > 0is false and it is the first check reached. - The second call becomes
bake(200, 50). Is10000allowed?
No: check 3 throws, because10000 < 10000is false.. The boundary value fails a strict<. - The program is run without
-ea. What prints?
It prints3600,12000,shelf clear.. All checks are skipped.
The first false assert ends the run (-ea)
- All three checks of
bake(180, 20)are true, so they are silent.mainprints3600. - In
bake(200, 60), checks 1 and 2 pass andheatis 12000. Check 3 is false, so anAssertionErrorwith its detail is thrown. bakenever returns a value, so the secondprintlninmaincannot run.- Nobody catches it. The program stops with the error;
shelf clearis 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.
badge("AB12"): the length is 4 and the text is notnull.badge AB12prints.badge(null): check 1 callscode.length()onnull.- That call throws a
NullPointerExceptionwhile the condition is being calculated. - 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.
"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
| Command | Classes with checks on |
|---|---|
java Main | none |
java -ea Main | all your classes |
java -ea:Ride Main | Ride only |
java -ea -da:Gate Main | all 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.
- Only
Rideis on.GateandMainare off. Ride.board(150)runs its check, which is true, so it silently returns:ride trueprints.Gate.admit(10)skips its false check and returnstrue:gate trueprints.Ride.board(100)runs its check:100 >= 120is false.- An
AssertionErrorwith messageride: too shortis thrown.enjoynever 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.
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 printsride 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 printsride true, then throws inGate.. Both classes check now: height 150 passes, and age 10 fails. - The command is
java -ea:Main Main. What prints?
It printsride true,gate true,ride true,enjoy..Mainis 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.
- Without
-eathe whole statement is skipped, sosensorOk()is never called:reads 0. - With
-eathe condition is calculated:sensorOk()adds 1 and returnstrue. - 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 MainOne class
java -ea:Ride MainThe difference. The text :Ride.
-ea alone enables all your classes; -ea:Name enables Name and leaves the others off.
"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.