🎯 What you will learn
- Catch exceptions with try/catch
- Use finally for clean-up
- Throw exceptions for invalid data
👋 Let’s get started!
Users type the wrong thing, files go missing, networks drop 🧯. Exceptions let Java programs handle problems gracefully instead of crashing.
🪜 Step by step
1. 🧯 try / catch
Put risky code in try; handle problems in catch.
try {
int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("That’s not a number!");
}
2. 🧹 finally
finally always runs — perfect for clean-up.
try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("Can’t divide by zero");
} finally {
System.out.println("Done checking");
}
3. 🚨 throw
Throw an exception when data is invalid.
void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age can’t be negative");
}
this.age = age;
}
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
Safe input parser
String[] inputs = { "42", "hello", "7" };
int total = 0;
for (String s : inputs) {
try {
total += Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("Skipping \"" + s + "\"");
}
}
System.out.println("Total: " + total);Catch division by zero
try {
int r = 8 / 0;
} catch (ArithmeticException e) {
System.out.println("Oops!");
}📖 Key words
Tap a card to flip it over!
- Exception
- An error event Java can handle 🧯
- try/catch
- Runs risky code and handles errors 🥅
- finally
- Always runs 🧹
- throw
- Raises an exception on purpose 🚨
🏆 Challenge
Predict the output.
Challenge
try {
String s = null;
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("Nothing there!");
} finally {
System.out.println("Bye");
}Knowledge Check Quiz
- When does finally run?
- Which exception does Integer.parseInt("hi") cause?
- Why throw exceptions?