java · level 2 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
an exception when a value makes no sense.
Your setters quietly ignored bad values, so nobody ever found out. Louder is often better. throw new IllegalArgumentException("Age cannot be negative"); stops the method at once and hands the problem to whoever called it. They can catch it, or the program stops.
IllegalArgumentException belongs to the family, the unchecked exceptions. Java does not force anyone to catch them, because they usually mean a mistake in the calling code, which should be fixed rather than handled.
public class Main {
static int ticketPrice(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative: " + age);
}
if (age < 16) {
return 5;
}
return 10;
}
public static void main(String[] args) {
try {
System.out.println(ticketPrice(12));
System.out.println(ticketPrice(-3));
System.out.println(ticketPrice(40));
} catch (IllegalArgumentException e) {
System.out.println("Problem: " + e.getMessage());
}
}
} The message you give the exception is what getMessage() hands back later.
guess first
A constructor that refuses. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class Box {
int size;
Box(int size) {
if (size <= 0) {
throw new IllegalArgumentException("A box needs a size");
}
this.size = size;
}
}
public static void main(String[] args) {
Box small = new Box(2);
System.out.println("Made a box of size " + small.size);
Box empty = new Box(0);
System.out.println("Made a box of size " + empty.size);
}
}
your turn
Your turn. Guard the bank.
On line 5, throw an IllegalArgumentException with a message of your own. Then press run: the -20 should be refused.
output
press run to see what happens
fix it
The volume guard will not compile. Fix it!
output
press run to see what happens
- Java says
cannot find symbolon line 4. It thinksIllegalArgumentException(...)is a method call. - An exception is an object, and objects are built with one small word.
- Change line 4 to
throw new IllegalArgumentException("Too loud: " + level);, then press run.
nailed it
you raised the alarm on bad values. :D
throw new IllegalArgumentException("...")refuses a bad value.- Throwing stops the method and hands the problem to the caller.
- Unchecked exceptions, the
RuntimeExceptionfamily, need nocatch.
new words in your collection
- throw
- unchecked exception
- RuntimeException
This lesson isn’t saved. A free account remembers every lesson you finish.