java-tutorial

8) Exceptions

Goal

Handle failures correctly: when to throw exceptions, how to catch them, and how to design error messages.

Checked vs unchecked

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

  1. Write a method that parses int from string and returns OptionalInt instead of throwing.
  2. Create a custom exception InsufficientFundsException and use it in withdraw.

Table of contents

  1. Getting Started: Install, run, and your first program
  2. Java Basics: types, variables, operators, formatting
  3. Control Flow: if/switch/loops
  4. Methods: parameters, return values, overloading
  5. OOP: classes, objects, encapsulation
  6. Inheritance & Polymorphism (and when not to use them)
  7. Interfaces, abstract classes, and design basics
  8. Exceptions and error handling
  9. Strings, files, and I/O basics
  10. Collections: List/Set/Map and Big-O intuition
  11. Generics (the useful parts)
  12. Lambdas & Streams
  13. Dates and time (java.time)
  14. Testing with JUnit 5 (basics)
  15. Concurrency: threads, executors, futures
  16. JVM basics: memory, GC, performance habits
  17. Build tools: Maven essentials (recommended)
  18. Next steps: projects to build