java · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Many problems, many catches, and a that always runs.
One try can have several catch blocks, one for each kind of problem. Java checks them from the top and runs only the first that matches. Dividing a whole number by zero, for example, gives an .
A finally block goes at the very end, and it always runs: after a clean try, after a catch, even while an uncaught exception is on its way out. It is the place to tidy up, like switching off the lights as you leave.
public class Main {
static void share(String sweets, int friends) {
try {
int each = Integer.parseInt(sweets) / friends;
System.out.println("Each friend gets " + each);
} catch (NumberFormatException e) {
System.out.println("That is not a number of sweets");
} catch (ArithmeticException e) {
System.out.println("Nobody to share with");
} finally {
System.out.println("Bag closed");
}
}
public static void main(String[] args) {
share("12", 4);
share("lots", 4);
share("12", 0);
}
} finally is the right home for goodbyes, saving work and closing things you opened.
guess first
When does finally run? Make a guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static String check(String text) {
try {
return "Got " + Integer.parseInt(text);
} catch (NumberFormatException e) {
return "Not a number";
} finally {
System.out.println("Checked " + text);
}
}
public static void main(String[] args) {
System.out.println(check("5"));
System.out.println(check("five"));
}
}
your turn
Your turn. Split the bill.
On line 5, fill in the exception that dividing by zero gives. On line 8, write a goodbye message of your own. Then press run.
output
press run to see what happens
fix it
The lights were left on. Fix it!
output
press run to see what happens
- After the second party goes wrong, the lights stay on. Why is line 7 skipped?
- When
parseIntfails, Java jumps tocatchand skips the rest oftry. A line that must always run needs its own block. - Move line 7 into a
finally { }block after thecatch, then press run.
nailed it
you handled every outcome. :D
- Several
catchblocks handle different problems, first match first. finallyalways runs, error or not.- Use
finallyfor tidying up.
new words in your collection
- ArithmeticException
- finally
This lesson isn’t saved. A free account remembers every lesson you finish.