java · level 2 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
the risky code, and the problem if it happens.
Type cake when asked for a number, and Integer.parseInt stops the whole program with a NumberFormatException. That is harsh. Wrap the risky lines in a try block, then add a catch block for that kind of exception.
If all goes well, the catch block is skipped. If the exception happens, Java jumps from the problem line straight into catch, skipping the rest of try. Either way, the program carries on afterwards.
Inside catch, e is the exception itself, and explains what went wrong.
public class Main {
public static void main(String[] args) {
String[] typed = {"12", "cake", "7"};
int total = 0;
for (String text : typed) {
try {
total = total + Integer.parseInt(text);
System.out.println("Added " + text);
} catch (NumberFormatException e) {
System.out.println("Skipped: " + e.getMessage());
}
}
System.out.println("Total: " + total);
}
} Catch only the exceptions you expect, so real bugs still show up.
guess first
Something goes wrong halfway. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
int[] marks = {8, 6};
try {
System.out.println("First: " + marks[0]);
System.out.println("Third: " + marks[2]);
System.out.println("Done reading");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No such mark");
}
System.out.println("Bye");
}
}
your turn
Your turn. Ask for an age, kindly.
Fill in the kind of exception to catch on line 9, and a friendly message of your own on line 10. Press run: the answer typed for you is ten, in words.
output
press run to see what happens
fix it
The wrong net catches nothing. Fix it!
output
press run to see what happens
- Java still stops with a
NumberFormatException. Which kind of exception does line 7 catch? - A
catchblock only handles its own kind of exception.ArrayIndexOutOfBoundsExceptionis a different one. - Change
ArrayIndexOutOfBoundsExceptiontoNumberFormatExceptionon line 7, then press run.
nailed it
your program keeps calm and carries on. :D
- Put risky lines in
try, and handle problems incatch. - After an exception, the rest of
tryis skipped. e.getMessage()explains what went wrong.
new words in your collection
- try
- catch
- getMessage
This lesson isn’t saved. A free account remembers every lesson you finish.