Exception

An Exception in Java is an object that represents an error or unexpected condition that disrupts normal program flow. Exceptions are thrown, caught, and can carry a message and a cause.

Exception hierarchy

Throwable
β”œβ”€β”€ Error        β€” serious JVM problems (OutOfMemoryError, StackOverflowError)
└── Exception
    β”œβ”€β”€ IOException, SQLException… β€” CHECKED exceptions
    └── RuntimeException            β€” UNCHECKED exceptions
        β”œβ”€β”€ NullPointerException
        β”œβ”€β”€ IllegalArgumentException
        β”œβ”€β”€ ClassCastException
        └── IndexOutOfBoundsException

Throwing and catching

public String readFile(String path) {
    try {
        return Files.readString(Path.of(path));
    } catch (IOException e) {
        throw new RuntimeException("Failed to read " + path, e);
    }
}

Checked vs unchecked

  • Checked (extends Exception but not RuntimeException) β€” compiler forces you to throws or catch.
  • Unchecked (extends RuntimeException) β€” compiler doesn't require handling. Used for programming errors.

try-with-resources

try (var reader = Files.newBufferedReader(path)) {
    // resource is auto-closed even if an exception is thrown
    return reader.readLine();
}

Exception chaining

throw new BusinessException("order failed", ioException);

Always include the cause β€” losing the stack trace of the original problem is a common debugging nightmare.