Lab 04: Exception Handling & Result Type

Objective

Build a typed exception hierarchy, practice multi-catch, try-with-resources, finally, and implement the Result type pattern using sealed interfaces for exception-free error propagation.

Background

Java distinguishes checked exceptions (must be declared/caught) from unchecked RuntimeException subclasses (optional). Well-designed exception hierarchies with meaningful error codes let callers react to specific failures without parsing message strings. The Result<T> pattern (borrowed from functional languages) is increasingly popular in Java 21 codebases.

Time

25 minutes

Prerequisites

  • Lab 03 (Functional Interfaces)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Step 1: Custom Exception Hierarchy

💡 RuntimeException vs checked exceptions: Checked exceptions (like IOException) force callers to handle them — good for recoverable conditions callers must plan for. RuntimeException subclasses are unchecked — good for programming errors and domain violations where every call site shouldn't be cluttered with try/catch. Modern Java style prefers unchecked exceptions with descriptive codes over checked exceptions.

📸 Verified Output:


Summary

Pattern
Use when

Custom RuntimeException hierarchy

Domain-specific errors with error codes

Multi-catch A | B

Same handling for multiple exception types

finally

Guaranteed cleanup (always runs)

try-with-resources

Auto-close AutoCloseable resources

Result<T> sealed

Exception-free error propagation in functional pipelines

Further Reading

Last updated