Guard clauses that fail fast
Each failed call leaves the balance untouched, because every check runs before the change.
throw is a statement that throws one exception object right now. throws is part of a method signature that warns callers which checked exceptions the method may pass up to them.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static double sqrtChecked(double x) that throws IllegalArgumentException with the value in the message for negative input. Call it with 9 and -4, catching and printing the message.
Write a class Door with open(), close() and lock(), where open() on a locked door and lock() on an open door throw IllegalStateException. Run a sequence that ends in an error and print each step.
Write static char grade(int marks) using a switch expression over marks / 10 that returns 'A' for 9 and 10, 'B' for 8, 'C' for 6 and 7, 'F' for 0..5, and throws for anything else. Test with 95, 72, 40 and 130.
Explain it without notes
What is the difference between throw and throws?
What is a guard clause, and which standard exceptions would you use in one?
Does throwing new IllegalStateException() through a variable of type Exception need a throws clause? Why?
Why does a method that ends with a call to an always-throwing helper fail to compile, and how do you fix it?
Expected output
withdraw 200: ok
withdraw -5: IllegalArgumentException - amount must be > 0, was -5
withdraw 900: IllegalStateException - insufficient funds: balance 300, asked 900
withdraw 10: IllegalStateException - account of Asha is frozen
new Account(null): NullPointerException - owner must not be null
new Account(-1): IllegalArgumentException - opening balance < 0: -1
balance left: 300