Skip to main content

Lesson 4 of 8

Custom Exceptions

Custom exceptions add meaning to error handling - instead of a generic RuntimeException, throw a BookNotFoundException with the searched ISBN. They let callers catch specific, named error conditions. Build a small exception hierarchy for the library system.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Custom Exception Hierarchy

Custom Exception Hierarchy
// Base exception for all library errors
public class LibraryException extends RuntimeException {
    private final String errorCode;

    public LibraryException(String message, String errorCode) {
        super(message);
        this.errorCode = errorCode;
    }

    public LibraryException(String message, String errorCode, Throwable cause) {
        super(message, cause);   // exception chaining!
        this.errorCode = errorCode;
    }

    public String getErrorCode() { return errorCode; }
}

// Specific exceptions - callers can catch just what they handle
public class BookNotFoundException extends LibraryException {
    private final String isbn;

    public BookNotFoundException(String isbn) {
        super("Book not found: ISBN=" + isbn, "BOOK_NOT_FOUND");
        this.isbn = isbn;
    }

    public String getIsbn() { return isbn; }
}

public class BookAlreadyBorrowedException extends LibraryException {
    private final String isbn;
    private final String borrowerId;

    public BookAlreadyBorrowedException(String isbn, String borrowerId) {
        super(String.format("Book '%s' is already borrowed by '%s'", isbn, borrowerId),
              "BOOK_BORROWED");
        this.isbn = isbn;
        this.borrowerId = borrowerId;
    }
}

public class InvalidIsbnException extends LibraryException {
    public InvalidIsbnException(String isbn) {
        super("Invalid ISBN format: " + isbn, "INVALID_ISBN");
    }
}

// Usage in service
public class LibraryService {
    private final LibraryCatalog catalog;

    public void borrowBook(String isbn, String memberId) {
        Book book = catalog.findByIsbn(isbn)
            .orElseThrow(() -> new BookNotFoundException(isbn));

        if (!book.isAvailable()) {
            throw new BookAlreadyBorrowedException(isbn, "another_member");
        }

        book.borrow();
    }

    // Caller catches only what it handles
    public void handleCheckout(String isbn, String memberId) {
        try {
            borrowBook(isbn, memberId);
            System.out.println("✓ Checkout successful");
        } catch (BookNotFoundException e) {
            System.err.println("Book not in catalog: " + e.getIsbn());
        } catch (BookAlreadyBorrowedException e) {
            System.err.println("Unavailable: " + e.getMessage() + " [" + e.getErrorCode() + "]");
        }
        // LibraryException and other RuntimeExceptions propagate up
    }
}

Quick Quiz

Tip

Tip

Practice Custom Exceptions 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 Custom Exceptions

Practice Task

Note

Practice Task - (1) Write a working example of Custom Exceptions 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 Custom Exceptions 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