Skip to main content

Lesson 7 of 8

Mini Project: Library System - Part 6 (Exception Handling)

Apply comprehensive exception handling to the Library System - custom exception hierarchy, guard clauses in all service methods, try-with-resources for file I/O, proper logging patterns, and a graceful error boundary in the main application.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Exception-Hardened Library Service

Exception-Hardened Library Service
import java.util.*;
import java.util.logging.*;

public class LibraryService {
    private static final Logger LOG = Logger.getLogger(LibraryService.class.getName());
    private final LibraryCatalog catalog;
    private final Map<String, List<BorrowRecord>> memberRecords = new HashMap<>();

    public LibraryService(LibraryCatalog catalog) {
        this.catalog = Objects.requireNonNull(catalog, "catalog must not be null");
    }

    public BorrowRecord checkout(String isbn, String memberId) {
        // Guard clauses
        Objects.requireNonNull(isbn,     "isbn must not be null");
        Objects.requireNonNull(memberId, "memberId must not be null");
        if (isbn.isBlank())     throw new InvalidIsbnException(isbn);
        if (memberId.isBlank()) throw new IllegalArgumentException("memberId blank");

        // Domain operation
        Book book = catalog.findByIsbn(isbn)
            .orElseThrow(() -> new BookNotFoundException(isbn));

        if (!book.isAvailable())
            throw new BookAlreadyBorrowedException(isbn, memberId);

        book.borrow();
        BorrowRecord record = new BorrowRecord(book, memberId);
        memberRecords.computeIfAbsent(memberId, k -> new ArrayList<>()).add(record);

        LOG.info(String.format("Checkout: isbn=%s member=%s due=%s",
                               isbn, memberId, record.getDueDate()));
        return record;
    }

    // Main app: graceful error boundary
    public static void main(String[] args) {
        var catalog = new LibraryCatalog();
        var service = new LibraryService(catalog);

        // All errors handled at top level - never crash without a message
        try {
            service.checkout("ISBN-001", "MBR-001");
        } catch (BookNotFoundException e) {
            System.err.println("ERROR [" + e.getErrorCode() + "]: " + e.getMessage());
        } catch (BookAlreadyBorrowedException e) {
            System.err.println("ERROR [" + e.getErrorCode() + "]: " + e.getMessage());
        } catch (LibraryException e) {
            System.err.println("ERROR [" + e.getErrorCode() + "]: " + e.getMessage());
        } catch (Exception e) {
            // Catch-all for unexpected errors - log + friendly message
            LOG.log(Level.SEVERE, "Unexpected error during checkout", e);
            System.err.println("Unexpected error. Please contact support.");
        }
    }
}

Quick Quiz

Tip

Tip

Practice Mini Project Library System Part 6 Exception Handling in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Library System - Part 6 (Exception Handling)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Library System Part 6 Exception Handling from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Mini Project Library System Part 6 Exception Handling is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done