🎯 What you will learn
Unhandled exceptions crash production services. In banking software, a failed CSV parse or a dropped DB connection must be caught, logged, and recovered — or at minimum surfaced with useful context. By the end of this lesson you will understand:
- Checked vs unchecked exceptions — when does the compiler force handling?
try / catch / finallyblocks and their execution order- Multi-catch and re-throwing exceptions
- Defining custom checked and unchecked exception classes
try-with-resourcesand theAutoCloseableinterface- Suppressed exceptions — how Java preserves both errors
🏦 Real-world scenario
SouthBank India's nightly batch reads thousands of CSV rows with payment amounts, looks up accounts in a database, and writes to a ledger. Arjun needs to: gracefully handle blank/malformed CSV values (IOException), surface missing accounts (IllegalArgumentException), define InsufficientFundsException with shortfall amount, and ensure DB connections are always released — even when exceptions occur — using try-with-resources.
⚠️ Checked and unchecked exceptions
Java has two families. Checked exceptions (extend Exception but not RuntimeException) must be declared in throws or caught — the compiler enforces this. Unchecked exceptions (extend RuntimeException) are optional to handle — they represent programming errors, not recoverable conditions.
finally always runs — whether or not an exception was thrown, and whether or not it was caught. The only exceptions: System.exit() called inside the try, or a JVM crash. Use finally for cleanup when not using try-with-resources.
🏗️ Custom exception classes
Define a custom exception when callers need to distinguish your error by type, or when you want to carry domain-specific data alongside the message. Extend Exception for checked, RuntimeException for unchecked.
🔌 try-with-resources and AutoCloseable
Any class implementing AutoCloseable can be declared in the try() header. Java guarantees close() is called at the end of the block — even if an exception was thrown. Multiple resources are closed in reverse declaration order.
📋 Exception hierarchy
| Type | Must handle? | Base class | Examples |
|---|---|---|---|
| Checked | Yes (catch or throws) | Exception | IOException, SQLException |
| Unchecked | Optional | RuntimeException | NullPointerException, IllegalArgumentException |
| Error | Do not catch | Error | OutOfMemoryError, StackOverflowError |
🧩 Mini challenge
Write a method parseRow(String row) that parses a CSV row "accountId,amount". Throw IllegalArgumentException for a blank row, NumberFormatException for bad amounts, and use a multi-catch block catch (IllegalArgumentException | NumberFormatException e) in the caller. Test with valid and invalid rows.
Catch a NumberFormatException inside parseAmount and rethrow it as an IOException with the original as the cause: throw new IOException("Bad format: " + raw, e). In the caller, print e.getCause().getMessage() to confirm the chain is preserved.
Implement a CsvReader class with AutoCloseable: the constructor prints "CSV opened", String nextLine() returns successive lines from a fixed array, and close() prints "CSV closed". Use it in a try-with-resources loop. Verify that close() is called even if an exception is thrown mid-read.
🎤 Interview Q&A
Checked exceptions extend Exception (but not RuntimeException) — the compiler forces you to handle or declare them. They represent recoverable conditions (file not found, network timeout). Unchecked exceptions extend RuntimeException — no compiler enforcement. They represent programming errors (null pointer, array out of bounds) where recovery is usually not expected. The debate over checked exceptions is ongoing; many modern APIs (Spring, Kotlin) prefer unchecked.
try-with-resources guarantee over a manual finally block?It guarantees close() is always called, even if the resource's own close() throws. If both the try body and close() throw, the close exception is attached as a suppressed exception (e.getSuppressed()) rather than masking the original. Manual finally blocks silently discard the original exception if close also throws.
Create a custom exception when: (1) callers need to distinguish your error from other exceptions by type — e.g., InsufficientFundsException vs generic Exception; (2) you want to carry additional context (like shortfall amount); (3) your library has a domain-specific error model. Don't create custom exceptions just to wrap a message — use IllegalArgumentException or IllegalStateException for standard programming-error patterns.
Lambdas cannot declare throws. Options: (1) wrap the checked exception in a RuntimeException: catch (IOException e) { throw new RuntimeException(e); }; (2) use a utility functional interface that declares throws Exception; (3) restructure code to handle the exception outside the lambda. Libraries like Lombok (@SneakyThrows) and Vavr provide utilities for this pattern.
When a try-with-resources block both throws an exception AND a resource's close() also throws, Java attaches the close() exception to the primary exception as a suppressed exception (accessible via Throwable.getSuppressed()). This preserves the original exception as the "real" failure while not silently losing the close failure. Prior to Java 7 with manual finally blocks, whichever exception was thrown last would suppress the original — a subtle and hard-to-debug issue.
📝 Quiz — 5 questions
finally block runs:try-with-resources calls close():RuntimeException is:Next: Spring Boot — Arc D starts here →
⚠️ Common mistakes
catch (Exception e) swallows everything including programming errors. Catch the most specific type first; use Exception only as a last-resort catch-all with logging.catch (IOException e) {} silently discards the error. Always log or rethrow. An empty catch block is almost always wrong and a code smell.finally is error-prone: the close itself can throw, masking the original exception. try-with-resources handles this correctly with suppressed exceptions.throws. Wrap checked exceptions in a RuntimeException or use a utility method that wraps the call.✅ Key takeaways
- Checked: compiler forces handling (
IOException,SQLException). Unchecked: optional (RuntimeException). finallyalways runs — use it for cleanup when not using try-with-resources.try-with-resourcesauto-callsclose()in reverse order; handles suppressed exceptions correctly.- Custom exceptions carry domain context; extend
Exceptionfor checked,RuntimeExceptionfor unchecked. - Never swallow exceptions with empty catch blocks.
From exceptions to production Spring Boot
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →