8) Exceptions
Goal
Handle failures correctly: when to throw exceptions, how to catch them, and how to design error messages.
Checked vs unchecked
- Unchecked exceptions: extend
RuntimeException (common for programming errors).
- Checked exceptions: must be declared/handled (common with I/O).
Throwing exceptions
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
try/catch/finally
try {
int x = Integer.parseInt("123");
System.out.println(x);
} catch (NumberFormatException e) {
System.out.println("Not a number");
} finally {
// runs even if exception occurs
}
try-with-resources
Use it for resources like files/streams:
try (var reader = Files.newBufferedReader(Path.of("data.txt"))) {
System.out.println(reader.readLine());
}
Exercises
- Write a method that parses int from string and returns
OptionalInt instead of throwing.
- Create a custom exception
InsufficientFundsException and use it in withdraw.
Table of contents
- Getting Started: Install, run, and your first program
- Java Basics: types, variables, operators, formatting
- Control Flow: if/switch/loops
- Methods: parameters, return values, overloading
- OOP: classes, objects, encapsulation
- Inheritance & Polymorphism (and when not to use them)
- Interfaces, abstract classes, and design basics
- Exceptions and error handling
- Strings, files, and I/O basics
- Collections: List/Set/Map and Big-O intuition
- Generics (the useful parts)
- Lambdas & Streams
- Dates and time (java.time)
- Testing with JUnit 5 (basics)
- Concurrency: threads, executors, futures
- JVM basics: memory, GC, performance habits
- Build tools: Maven essentials (recommended)
- Next steps: projects to build