Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 11 / Stage 2

I/O, APIs and databases

Goal: Design exceptions for your own APIs instead of just catching the JDK's, call a REST endpoint with java.net.http.HttpClient and read its JSON, talk to a real SQL database with JDBC through one external driver jar, write every query as a parameterized query, and use regex for the validation jobs that come up constantly in real code. Time: ~6 hours

What you will learn

  • A second, deeper pass on exceptions: checked vs. unchecked for your own classes, and wrapping a low-level cause
  • try-with-resources with more than one resource, close order, and suppressed exceptions
  • java.net.http.HttpClient: GET and POST, status codes, headers, timeouts
  • Why this part's HTTP examples talk to a local, JDK-only HttpServer instead of the real internet
  • Parsing JSON by hand with regex, and exactly where "by hand" stops being safe
  • JDBC architecture: DriverManager, Connection, Statement, ResultSet — and the one external jar this course adds
  • PreparedStatement and why string-concatenated SQL is an actual security hole, not just bad style
  • java.util.regex: Pattern, Matcher, named groups, find() vs. matches(), replaceAll(), split()
  • Putting it together: a weather lookup over HTTP(S), and an orders database with validated input

About "JDK 21.0.11 Corretto": every command and output below was run on the exact JDK pinned in ../../TOOLING.md. Database and HTTP output is otherwise stable across any JDK 21 build.

ℹ️ Still no build tool. Maven doesn't arrive until Stage 3 Part 15 (DESIGN-NOTES.md #8). This part needs its first artifact that isn't part of the JDK — a JDBC driver for SQLite — and it is managed the honest, manual way: one .jar file, on the classpath by hand, exactly like Part 7 managed multiple .java files before packages had any tooling behind them. The jar is already sitting in examples/lib/sqlite-jdbc-3.50.3.0.jar (org.xerial:sqlite-jdbc:3.50.3.0, from Maven Central); you don't need to download anything to run this part's examples.

Topics in this part

Practice

Try each one yourself first. Then check the solution.

Every exercise is one .java file with a public static void main(String[] args) method, the same shape as every example in this part. solutions/ex01.java through ex08.java use a non-public top-level class (class Ex01 { ... }, matching the stage-wide convention from Part 1) so the filename does not need to match the class name. Exercises 6, 7 and 8 need the SQLite driver jar on the classpath for both javac and java — the exact same commands Part 11's own JDBC examples use, just pointed at ../examples/lib/sqlite-jdbc-3.50.3.0.jar from inside solutions/.


Exercise 1: Design a checked and an unchecked exception

Scenario: A train-seat booking counter. A taken seat is a normal, expected thing a clerk recovers from instantly by trying another seat. The booking system itself being down is not something the clerk can fix mid-transaction. What to do:

  1. Write a checked SeatTakenException(message) and throw it from a bookSeat(seat) method when the seat is already in a Set<String> of taken seats (seed it with "A1" and "A2"); otherwise add the seat and print Booked seat <seat>.
  2. Write an unchecked BookingSystemException(message, cause) and throw it from bookSeatOrFail(seat, systemDown) when systemDown is true, wrapping a plain RuntimeException("booking service timed out after 5000ms") as the cause.
  3. In main, try to book "A1", "B1", "A2", "B2" one at a time, catching SeatTakenException around each call and printing a message that still tells the clerk to try another seat.
  4. Call bookSeatOrFail("C1", true), catch the BookingSystemException, and print its message and its cause.

Sample output:

Could not book A1: seat A1 is already booked -- try another seat
Booked seat B1
Could not book A2: seat A2 is already booked -- try another seat
Booked seat B2

Fatal: could not book seat C1: system unavailable
Caused by: java.lang.RuntimeException: booking service timed out after 5000ms

💡 Hint: SeatTakenException extends Exception; BookingSystemException extends RuntimeException with a constructor that calls super(message, cause) — that one call is what makes getCause() work later.


Exercise 2: Two resources, both fail on close

Scenario: An invoice printer and a label printer, both AutoCloseable. The label printer jams mid-print, and both printers then fail to park their print heads while closing. What to do:

  1. Write Printer(name, failOnClose) implementing AutoCloseable, with print(text) (prints <name>: <text>), printAndJam() (throws IllegalStateException("<name>: paper jam")), and close() that prints <name>: shutting down and, if failOnClose is true, throws IllegalStateException("<name>: could not park print head").
  2. In a try-with-resources opening an invoice printer and a label printer (both with failOnClose = true), print an invoice, then call printAndJam() on the label printer.
  3. Catch the IllegalStateException, print its message, then print e.getSuppressed().length and every suppressed exception's message.

Sample output:

Invoice printer: Invoice #4021
Label printer: shutting down
Invoice printer: shutting down
Caught: Label printer: paper jam
Suppressed count: 2
  suppressed: Label printer: could not park print head
  suppressed: Invoice printer: could not park print head

💡 Hint: Close order is the reverse of open order — the label printer (opened second) closes first. Both close() failures land in getSuppressed(), in the order they happened, on the exception the try body actually threw.


Exercise 3: A local notes API with HttpClient

Scenario: A tiny notes app: GET /notes/{id} fetches one note, POST /notes creates one, served by a local HttpServer (no public internet involved). What to do:

  1. Start a com.sun.net.httpserver.HttpServer on localhost with port 0. Seed a Map<Integer, String> with note 1 as {"id":1,"text":"Buy milk"}.
  2. In the /notes context: for GET /notes/{id}, return the stored JSON with status 200, or {"error":"no note <id>"} with status 404 if missing. For POST /notes, read the request body, assign the next id, store it, and return it with status 201.
  3. With HttpClient, GET note 1, GET note 99 (missing), then POST a new note {"id":0,"text":"Call Ravi"}. Print each call's status code and body.
  4. Stop the server.

Sample output:

GET /notes/1 -> 200 {"id":1,"text":"Buy milk"}
GET /notes/99 -> 404 {"error":"no note 99"}
POST /notes -> 201 {"id":2,"text":"Call Ravi"}

💡 Hint: Read the request path with exchange.getRequestURI().getPath() and split it on /; read a POST body with exchange.getRequestBody().readAllBytes(). Every HttpServer exchange must end with exchange.close(), or the client just hangs waiting for a response.


Exercise 4: Validate a vehicle registration number

Scenario: An Indian vehicle plate has the shape: 2 letters (state), 2 digits (RTO code), 1–2 letters (series), 4 digits (serial) — for example MH12AB1234. What to do:

  1. Write a Pattern with named groups state, rto, series, serial matching that exact shape, anchored to the whole string.
  2. For each plate in {"MH12AB1234", "DL3C0917", "KA01X5530", "mh12ab1234", "MH1AB1234"}, print either <plate> -> valid, state=<state> rto=<rto> serial=<serial> or <plate> -> invalid.

Sample output:

MH12AB1234 -> valid, state=MH rto=12 serial=1234
DL3C0917 -> invalid
KA01X5530 -> valid, state=KA rto=01 serial=5530
mh12ab1234 -> invalid
MH1AB1234 -> invalid

💡 Hint: DL3C0917 fails because after the 2-letter state (DL) the pattern needs 2 digits, and the input has 3C there — one digit, one letter. Regex is case-sensitive by default, which is why the lower-case plate also fails.


Exercise 5: Flat JSON by hand, and where it breaks

Scenario: A product catalog's JSON sometimes nests a packaging object with its own weight field, and the by-hand parser has no idea the two weight fields mean different things. What to do:

  1. Write flatFields(json), the same regex-based field extractor from the README's section 6, returning a Map<String, String>.
  2. Parse {"name":"Pressure cooker","price":1899,"weight":2.5} and print the map, then name=<name>, weight=<weight>kg.
  3. Parse {"name":"Pressure cooker","weight":2.5,"packaging":{"weight":0.4,"material":"cardboard"}} with the same function, print the map, then print which weight it picked up and ask out loud whether that's the product's own weight or the packaging's.

Sample output:

flat: {name=Pressure cooker, price=1899, weight=2.5}
name=Pressure cooker, weight=2.5kg
nested: {name=Pressure cooker, weight=0.4, material=cardboard}
weight picked up: 0.4kg (the product's own weight, or the packaging's?)

💡 Hint: The regex finds every "key": value pair in the whole string, in order, with no idea which { } it came from — the second "weight" match simply overwrites the first one in the map, the same silent bug as the README's weather example.


Exercise 6: A students table over JDBC

Scenario: A teacher wants a small SQLite table of students and their marks, queried highest-first. What to do:

  1. Connect to a fresh SQLite database file data/ex06-students.db (delete it first if it already exists, so every run starts clean).
  2. Create a students table (id auto-increment primary key, name TEXT, marks INTEGER), then insert ("Asha", 88), ("Ravi", 95), ("Meera", 76) in one executeUpdate.
  3. Query all students ordered by marks DESC and print <name>: <marks> for each.
  4. Query COUNT(*) and AVG(marks) in one aggregate query and print total: <n>, average: <avg to 2 decimals>.

Sample output:

-- students, highest marks first --
Ravi: 95
Asha: 88
Meera: 76
total: 3, average: 86.33

💡 Hint: AUTOINCREMENT needs INTEGER PRIMARY KEY exactly (SQLite's own rule); String.format/printf's %.2f rounds the average for you.


Exercise 7: Break and fix a login check

Scenario: A login check built with string-concatenated SQL. Prove it can be broken into without the real password, then fix it. What to do:

  1. Create a SQLite table users(username TEXT, password TEXT) with one row: ("asha", "secret123").
  2. Write unsafeLogin(connection, username, password): build SELECT 1 FROM users WHERE username = '<username>' AND password = '<password>' by string concatenation, print the SQL you are about to send, run it, and return whether any row came back.
  3. Write safeLogin(connection, username, password): the same check with a PreparedStatement and two ? placeholders.
  4. Call unsafeLogin with username "asha" and password ' OR '1'='1. Print whether it logged in.
  5. Call safeLogin with the exact same attacker password, print the result, then call safeLogin again with the real password "secret123" and print that result too.

Sample output:

-- VULNERABLE: attacker never knows the real password --
SQL sent: SELECT 1 FROM users WHERE username = 'asha' AND password = '' OR '1'='1'
logged in without the real password: true

-- SAFE: the same attack, through a PreparedStatement --
logged in without the real password: false

-- SAFE: a legitimate login still works --
logged in with the real password: true

💡 Hint: The attacker's text closes the password = '...' quote early and appends OR '1'='1', which is always true, so the whole WHERE clause is always true. A PreparedStatement sends that same text as one literal value — no real password is ever equal to it, so step 4's attack still returns false once it's parameterized.


Exercise 8: A members database, start to finish

Scenario: A club's membership list: every email checked by regex before it is ever written, every query parameterized, every database failure wrapped in one clear exception type. What to do:

  1. Write MemberStoreException extends RuntimeException with a (message, cause) constructor.
  2. Write a class wrapping a Connection with: createTable() (a members table: id, name, email); addMember(name, email) — reject with IllegalArgumentException if the email fails a reasonable [email protected] regex, otherwise insert with a PreparedStatement and return the generated id; findByNameLike(fragment) — a parameterized LIKE '%<fragment>%' query (still with ?, never concatenated) returning a List of record Member(int id, String name, String email), ordered by name. Wrap every SQLException from any of these three methods in a MemberStoreException.
  3. In main, add "Asha Kulkarni" / "[email protected]", "Arjun Kulkarni" / "[email protected]", "Ravi Shah" / "[email protected]", printing the generated id after each.
  4. Try adding "Bad Email" / "not-an-email", catch the IllegalArgumentException, and print that it was rejected before any query ran.
  5. Search for "Kulkarni" and print every match as #<id> <name> <<email>>.

Sample output:

-- adding members, email validated by regex first --
added #1 (Asha)
added #2 (Arjun)
added #3 (Ravi)
rejected before any query ran: not a valid email: not-an-email

-- members matching 'Kulkarni' --
#2 Arjun Kulkarni <[email protected]>
#1 Asha Kulkarni <[email protected]>

💡 Hint: Statement.RETURN_GENERATED_KEYS on prepareStatement, then statement.getGeneratedKeys() after executeUpdate(), is how you get the new row's auto-incremented id back without a second query. Build the LIKE pattern ("%" + fragment + "%") in Java and still pass it through setString, never by gluing it into the SQL text.

Show the solutions for Part 11 (8 files)

solutions/ex01.java

// Exercise 1: a checked exception for a recoverable booking problem
// (try a different seat), and an unchecked exception for the booking
// system itself being unavailable, wrapping the low-level cause.

class SeatTakenException extends Exception {           // checked: the caller can pick another seat right now
    SeatTakenException(String message) {
        super(message);
    }
}

class BookingSystemException extends RuntimeException { // unchecked: nothing to do inline, the system is down
    BookingSystemException(String message, Throwable cause) {
        super(message, cause);
    }
}

class Ex01 {

    static java.util.Set<String> takenSeats = new java.util.HashSet<>(java.util.List.of("A1", "A2"));

    static void bookSeat(String seat) throws SeatTakenException {
        if (takenSeats.contains(seat)) {
            throw new SeatTakenException("seat " + seat + " is already booked");
        }
        takenSeats.add(seat);
        System.out.println("Booked seat " + seat);
    }

    static void bookSeatOrFail(String seat, boolean systemDown) {
        if (systemDown) {
            RuntimeException lowLevel = new RuntimeException("booking service timed out after 5000ms");
            throw new BookingSystemException("could not book seat " + seat + ": system unavailable", lowLevel);
        }
        System.out.println("Booked seat " + seat + " (system check passed)");
    }

    public static void main(String[] args) {
        for (String seat : new String[]{"A1", "B1", "A2", "B2"}) {
            try {
                bookSeat(seat);
            } catch (SeatTakenException e) {
                System.out.println("Could not book " + seat + ": " + e.getMessage() + " -- try another seat");
            }
        }

        System.out.println();
        try {
            bookSeatOrFail("C1", true);
        } catch (BookingSystemException e) {
            System.out.println("Fatal: " + e.getMessage());
            System.out.println("Caused by: " + e.getCause());
        }
    }
}

solutions/ex02.java

// Exercise 2: two AutoCloseable "printer" resources; the second one's
// print() fails, and BOTH close() calls also fail -- show every
// suppressed exception that ends up attached to the one you catch.

class Printer implements AutoCloseable {
    private final String name;
    private final boolean failOnClose;

    Printer(String name, boolean failOnClose) {
        this.name = name;
        this.failOnClose = failOnClose;
    }

    void print(String text) {
        System.out.println(name + ": " + text);
    }

    void printAndJam() {
        throw new IllegalStateException(name + ": paper jam");
    }

    @Override
    public void close() {
        System.out.println(name + ": shutting down");
        if (failOnClose) {
            throw new IllegalStateException(name + ": could not park print head");
        }
    }
}

class Ex02 {
    public static void main(String[] args) {
        try (Printer invoicePrinter = new Printer("Invoice printer", true);
             Printer labelPrinter = new Printer("Label printer", true)) {
            invoicePrinter.print("Invoice #4021");
            labelPrinter.printAndJam();
        } catch (IllegalStateException e) {
            System.out.println("Caught: " + e.getMessage());
            Throwable[] suppressed = e.getSuppressed();
            System.out.println("Suppressed count: " + suppressed.length);
            for (Throwable s : suppressed) {
                System.out.println("  suppressed: " + s.getMessage());
            }
        }
    }
}

solutions/ex03.java

// Exercise 3: a local "notes" API (GET /notes/{id}, POST /notes) served
// by com.sun.net.httpserver.HttpServer, called with HttpClient.

import com.sun.net.httpserver.HttpServer;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

class Ex03 {
    public static void main(String[] args) throws Exception {
        Map<Integer, String> notes = new ConcurrentHashMap<>();
        notes.put(1, "{\"id\":1,\"text\":\"Buy milk\"}");
        AtomicInteger nextId = new AtomicInteger(2);

        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/notes", exchange -> {
            String method = exchange.getRequestMethod();
            String[] parts = exchange.getRequestURI().getPath().split("/");
            byte[] bytes;
            int status;
            if ("GET".equals(method) && parts.length == 3) {
                int id = Integer.parseInt(parts[2]);
                String json = notes.get(id);
                status = json != null ? 200 : 404;
                bytes = (json != null ? json : "{\"error\":\"no note " + id + "\"}").getBytes(StandardCharsets.UTF_8);
            } else if ("POST".equals(method)) {
                String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
                int id = nextId.getAndIncrement();
                String stored = body.replace("\"id\":0", "\"id\":" + id);
                notes.put(id, stored);
                bytes = stored.getBytes(StandardCharsets.UTF_8);
                status = 201;
            } else {
                bytes = new byte[0];
                status = 405;
            }
            exchange.getResponseHeaders().add("Content-Type", "application/json");
            exchange.sendResponseHeaders(status, bytes.length);
            exchange.getResponseBody().write(bytes);
            exchange.close();
        });
        server.start();
        URI base = URI.create("http://localhost:" + server.getAddress().getPort());
        HttpClient client = HttpClient.newHttpClient();

        HttpRequest getRequest = HttpRequest.newBuilder(base.resolve("/notes/1")).GET().build();
        HttpResponse<String> getResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println("GET /notes/1 -> " + getResponse.statusCode() + " " + getResponse.body());

        HttpRequest missingRequest = HttpRequest.newBuilder(base.resolve("/notes/99")).GET().build();
        HttpResponse<String> missingResponse = client.send(missingRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println("GET /notes/99 -> " + missingResponse.statusCode() + " " + missingResponse.body());

        HttpRequest postRequest = HttpRequest.newBuilder(base.resolve("/notes"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString("{\"id\":0,\"text\":\"Call Ravi\"}"))
                .build();
        HttpResponse<String> postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println("POST /notes -> " + postResponse.statusCode() + " " + postResponse.body());

        server.stop(0);
    }
}

solutions/ex04.java

// Exercise 4: validate an Indian vehicle registration number shape
// (2 letters, 2 digits, 1-2 letters, 4 digits) and pull out the state
// code and the serial number with named groups.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ex04 {
    public static void main(String[] args) {
        Pattern platePattern = Pattern.compile(
                "^(?<state>[A-Z]{2})(?<rto>\\d{2})(?<series>[A-Z]{1,2})(?<serial>\\d{4})$");

        String[] plates = {"MH12AB1234", "DL3C0917", "KA01X5530", "mh12ab1234", "MH1AB1234"};
        for (String plate : plates) {
            Matcher matcher = platePattern.matcher(plate);
            if (matcher.matches()) {
                System.out.println(plate + " -> valid, state=" + matcher.group("state")
                        + " rto=" + matcher.group("rto") + " serial=" + matcher.group("serial"));
            } else {
                System.out.println(plate + " -> invalid");
            }
        }
    }
}

solutions/ex05.java

// Exercise 5: parse a flat product JSON by hand with regex, then show
// the same approach silently picking the wrong "weight" once the JSON
// has a nested "packaging" object with its own weight field.

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ex05 {

    static Map<String, String> flatFields(String json) {
        Map<String, String> fields = new LinkedHashMap<>();
        Pattern fieldPattern = Pattern.compile(
                "\"(\\w+)\"\\s*:\\s*(\"([^\"]*)\"|-?\\d+(\\.\\d+)?)");
        Matcher matcher = fieldPattern.matcher(json);
        while (matcher.find()) {
            fields.put(matcher.group(1), matcher.group(3) != null ? matcher.group(3) : matcher.group(2));
        }
        return fields;
    }

    public static void main(String[] args) {
        String flatJson = "{\"name\":\"Pressure cooker\",\"price\":1899,\"weight\":2.5}";
        Map<String, String> flat = flatFields(flatJson);
        System.out.println("flat: " + flat);
        System.out.println("name=" + flat.get("name") + ", weight=" + flat.get("weight") + "kg");

        String nestedJson = "{\"name\":\"Pressure cooker\",\"weight\":2.5,"
                + "\"packaging\":{\"weight\":0.4,\"material\":\"cardboard\"}}";
        Map<String, String> nested = flatFields(nestedJson);
        System.out.println("nested: " + nested);
        System.out.println("weight picked up: " + nested.get("weight")
                + "kg (the product's own weight, or the packaging's?)");
    }
}

solutions/ex06.java

// Exercise 6: JDBC basics -- create a "students" table in SQLite,
// insert rows, and query them back ordered by marks.
// Compile/run with the SQLite driver jar on BOTH classpaths:
//   javac -cp ../examples/lib/sqlite-jdbc-3.50.3.0.jar ex06.java
//   java  -cp .:../examples/lib/sqlite-jdbc-3.50.3.0.jar Ex06

import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

class Ex06 {
    public static void main(String[] args) throws Exception {
        Path dbFile = Path.of("data", "ex06-students.db");
        Files.createDirectories(dbFile.getParent());
        Files.deleteIfExists(dbFile);

        try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile)) {
            try (Statement statement = connection.createStatement()) {
                statement.execute("""
                        CREATE TABLE students (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            name TEXT NOT NULL,
                            marks INTEGER NOT NULL
                        )
                        """);
                statement.executeUpdate("""
                        INSERT INTO students (name, marks) VALUES
                            ('Asha', 88),
                            ('Ravi', 95),
                            ('Meera', 76)
                        """);

                System.out.println("-- students, highest marks first --");
                try (ResultSet rows = statement.executeQuery(
                        "SELECT name, marks FROM students ORDER BY marks DESC")) {
                    while (rows.next()) {
                        System.out.println(rows.getString("name") + ": " + rows.getInt("marks"));
                    }
                }

                try (ResultSet summary = statement.executeQuery(
                        "SELECT COUNT(*) AS total, AVG(marks) AS avg_marks FROM students")) {
                    summary.next();
                    System.out.printf("total: %d, average: %.2f%n", summary.getInt("total"), summary.getDouble("avg_marks"));
                }
            }
        }
    }
}

solutions/ex07.java

// Exercise 7: a login check vulnerable to SQL injection via string
// concatenation, then the same check made safe with PreparedStatement.
// Compile/run with the SQLite driver jar on BOTH classpaths:
//   javac -cp ../examples/lib/sqlite-jdbc-3.50.3.0.jar ex07.java
//   java  -cp .:../examples/lib/sqlite-jdbc-3.50.3.0.jar Ex07

import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

class Ex07 {

    static boolean unsafeLogin(Connection connection, String username, String password) throws Exception {
        String sql = "SELECT 1 FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
        System.out.println("SQL sent: " + sql);
        try (Statement statement = connection.createStatement();
             ResultSet rows = statement.executeQuery(sql)) {
            return rows.next();
        }
    }

    static boolean safeLogin(Connection connection, String username, String password) throws Exception {
        String sql = "SELECT 1 FROM users WHERE username = ? AND password = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, username);
            statement.setString(2, password);
            try (ResultSet rows = statement.executeQuery()) {
                return rows.next();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Path dbFile = Path.of("data", "ex07-users.db");
        Files.createDirectories(dbFile.getParent());
        Files.deleteIfExists(dbFile);

        try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile)) {
            try (Statement setup = connection.createStatement()) {
                setup.execute("CREATE TABLE users (username TEXT, password TEXT)");
                setup.executeUpdate("INSERT INTO users (username, password) VALUES ('asha', 'secret123')");
            }

            System.out.println("-- VULNERABLE: attacker never knows the real password --");
            String attackerPassword = "' OR '1'='1";
            boolean brokenIn = unsafeLogin(connection, "asha", attackerPassword);
            System.out.println("logged in without the real password: " + brokenIn);

            System.out.println();
            System.out.println("-- SAFE: the same attack, through a PreparedStatement --");
            boolean stillBrokenIn = safeLogin(connection, "asha", attackerPassword);
            System.out.println("logged in without the real password: " + stillBrokenIn);

            System.out.println();
            System.out.println("-- SAFE: a legitimate login still works --");
            boolean legitimate = safeLogin(connection, "asha", "secret123");
            System.out.println("logged in with the real password: " + legitimate);
        }
    }
}

solutions/ex08.java

// Exercise 8: putting it together -- a members database with a
// regex-validated email, parameterized queries, and a custom unchecked
// exception wrapping every SQLException.
// Compile/run with the SQLite driver jar on BOTH classpaths:
//   javac -cp ../examples/lib/sqlite-jdbc-3.50.3.0.jar ex08.java
//   java  -cp .:../examples/lib/sqlite-jdbc-3.50.3.0.jar Ex08

import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

class MemberStoreException extends RuntimeException {
    MemberStoreException(String message, Throwable cause) {
        super(message, cause);
    }
}

class Ex08 {

    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[a-zA-Z]{2,}$");

    record Member(int id, String name, String email) {
    }

    private final Connection connection;

    Ex08(Connection connection) {
        this.connection = connection;
    }

    void createTable() {
        try (Statement statement = connection.createStatement()) {
            statement.execute("""
                    CREATE TABLE members (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        name TEXT NOT NULL,
                        email TEXT NOT NULL
                    )
                    """);
        } catch (SQLException e) {
            throw new MemberStoreException("could not create the members table", e);
        }
    }

    int addMember(String name, String email) {
        if (!EMAIL_PATTERN.matcher(email).matches()) {
            throw new IllegalArgumentException("not a valid email: " + email);
        }
        String sql = "INSERT INTO members (name, email) VALUES (?, ?)";
        try (PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            statement.setString(1, name);
            statement.setString(2, email);
            statement.executeUpdate();
            try (ResultSet keys = statement.getGeneratedKeys()) {
                keys.next();
                return keys.getInt(1);
            }
        } catch (SQLException e) {
            throw new MemberStoreException("could not add member " + name, e);
        }
    }

    List<Member> findByNameLike(String fragment) {
        String sql = "SELECT id, name, email FROM members WHERE name LIKE ? ORDER BY name ASC";
        List<Member> results = new ArrayList<>();
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, "%" + fragment + "%");
            try (ResultSet rows = statement.executeQuery()) {
                while (rows.next()) {
                    results.add(new Member(rows.getInt("id"), rows.getString("name"), rows.getString("email")));
                }
            }
        } catch (SQLException e) {
            throw new MemberStoreException("could not search members for " + fragment, e);
        }
        return results;
    }

    public static void main(String[] args) throws Exception {
        Path dbFile = Path.of("data", "ex08-members.db");
        Files.createDirectories(dbFile.getParent());
        Files.deleteIfExists(dbFile);

        try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile)) {
            Ex08 store = new Ex08(connection);
            store.createTable();

            System.out.println("-- adding members, email validated by regex first --");
            int id1 = store.addMember("Asha Kulkarni", "[email protected]");
            System.out.println("added #" + id1 + " (Asha)");
            int id2 = store.addMember("Arjun Kulkarni", "[email protected]");
            System.out.println("added #" + id2 + " (Arjun)");
            int id3 = store.addMember("Ravi Shah", "[email protected]");
            System.out.println("added #" + id3 + " (Ravi)");

            try {
                store.addMember("Bad Email", "not-an-email");
            } catch (IllegalArgumentException e) {
                System.out.println("rejected before any query ran: " + e.getMessage());
            }

            System.out.println();
            System.out.println("-- members matching 'Kulkarni' --");
            for (Member member : store.findByNameLike("Kulkarni")) {
                System.out.println("#" + member.id() + " " + member.name() + " <" + member.email() + ">");
            }
        }
    }
}

Common mistakes

Mistake Why it is wrong Fix
Making every custom exception unchecked "to be simple" Forces callers to discover recoverable failures (a bad input line) only at runtime, by accident Checked for "the immediate caller can fix this"; unchecked for "nothing useful to do inline"
Swallowing a low-level exception instead of wrapping it getCause() is null, and debugging loses the real reason throw new YourException(message, originalException)
Reading e.getMessage() after a multi-resource try fails, and stopping there A close() failure sits silently in getSuppressed() Check getSuppressed() whenever a try-with-resources with real I/O resources can fail on close
Pointing HttpClient examples at a real website Breaks the moment that site changes, is slow, or needs auth you don't have A local com.sun.net.httpserver.HttpServer, started in the example itself
Checking response.body() without checking response.statusCode() first A 404/500 body is not an exception — trusting it as "the data" crashes or lies later Always branch on statusCode() before trusting the body
Regex-parsing JSON with any real nesting Two fields with the same name at different nesting levels collide silently (section 6) Flat JSON only; reach for Jackson/Gson once there's real structure
"SELECT * FROM t WHERE col = '" + userInput + "'" SQL injection — user input can change the query's structure, not just its data PreparedStatement with ? placeholders, always, for any value not hard-coded in your source
Forgetting the SQLite jar on both javac -cp and java -cp Compiles fine (if only javac had it) and then fails at runtime, or the reverse Put lib/sqlite-jdbc-3.50.3.0.jar on the classpath for both commands

Quick recap

  • Design your own exceptions the way the JDK's are designed: checked when the immediate caller can recover, unchecked when it can't, and wrap a low-level cause instead of discarding it.
  • try-with-resources closes resources in reverse of open order; if close() also fails after the body already threw, the close failures become suppressed exceptions on the one you catch.
  • HttpClient builds a request, send()s it with a BodyHandler, and never throws just because the status code is bad — check statusCode() yourself.
  • This course's HTTP examples run against a local, JDK-only HttpServer so they never depend on the public internet.
  • Regex (Pattern/Matcher) validates fixed, flat shapes well (phone numbers, pincodes) and parses flat JSON in a pinch, but has no concept of nesting — that's what a real JSON library is for.
  • JDBC needs a driver jar per database; this course's one external dependency is sqlite-jdbc, added by hand to -cp on both javac and java, no build tool yet.
  • Every query that includes a value from outside your source code must be a PreparedStatement with ? placeholders — string-concatenated SQL is a real security hole, not a style complaint.

Checklist

  • I can say, for one of my own exceptions, whether it should be checked or unchecked, and why.
  • I wrapped a low-level exception in my own exception class and read its cause back with getCause().
  • I triggered a suppressed exception on purpose and read it from getSuppressed().
  • I started a local HttpServer, called it with HttpClient (GET and POST), and read the status code, headers and body.
  • I wrote a regex with a named group and read a field back with matcher.group("name").
  • I parsed a flat JSON object by hand, and can explain why the same approach breaks on nested JSON.
  • I connected to a real SQLite database with JDBC, with the driver jar on the classpath for both javac and java.
  • I reproduced the SQL injection in ParameterizedQueryDemo.java myself, then fixed it with a PreparedStatement.
  • I built the orders database example end to end: regex validation, parameterized queries, wrapped exceptions.

Search the guide