java · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Make your own exception, and Java makes callers face it.
Some problems are nobody's fault: a shop runs out of stock, or a file goes missing. Java calls these checked exceptions. They extend Exception but not RuntimeException, and Java checks that every caller deals with them before the program can run.
Make a by extending Exception, with a constructor that hands the message to super. A method that can throw it says so with after its brackets. Each caller must then catch it, or declare it in turn.
public class Main {
static class OutOfStockException extends Exception {
OutOfStockException(String message) { super(message); }
}
static void buy(String cake, int left) throws OutOfStockException {
if (left == 0) {
throw new OutOfStockException("Sorry, no " + cake + " left");
}
System.out.println("One " + cake + ", coming up!");
}
public static void main(String[] args) {
try {
buy("cupcake", 3);
buy("eclair", 0);
} catch (OutOfStockException e) {
System.out.println(e.getMessage());
}
}
} Name an exception after its problem, and end the name with Exception.
guess first
Nobody dealt with it. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class TooColdException extends Exception {
TooColdException(String message) { super(message); }
}
static void swim(int degrees) throws TooColdException {
if (degrees < 15) {
throw new TooColdException("Brr! Only " + degrees + " degrees");
}
System.out.println("Splash!");
}
public static void main(String[] args) {
swim(20);
}
}
your turn
Your turn. Make your own exception.
On line 2, make NoSeatsException a checked exception by extending the right class. On line 5, warn that book can throw it. Put your name in on line 13, then press run.
output
press run to see what happens
fix it
The treasure chest never warned anyone. Fix it!
output
press run to see what happens
- Java says
unreported exception WrongCodeExceptionon line 7. A checked exception is thrown, but who was warned? - A method that can throw a checked exception must say so after its brackets.
- Change line 5 to
static void openChest(int code) throws WrongCodeException {, then press run.
nailed it
you made an exception of your own. :D
- Extend
Exceptionfor a checked exception named after the problem. throwswarns that a method can throw it.- Every caller must catch it or declare it too.
new words in your collection
- checked exception
- throws
- custom exception
This lesson isn’t saved. A free account remembers every lesson you finish.