🎯 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 / finally blocks and their execution order
  • Multi-catch and re-throwing exceptions
  • Defining custom checked and unchecked exception classes
  • try-with-resources and the AutoCloseable interface
  • Suppressed exceptions — how Java preserves both errors
💼 Interview reality: "What is the difference between checked and unchecked exceptions?" is one of the most common Java interview questions. "Explain try-with-resources" is equally common in mid-level rounds. Both are covered here with production-grade examples.

🏦 Real-world scenario

🏦
Real-world scenario · SouthBank India, Mumbai
Arjun hardens the payment processing pipeline

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.

javac CheckedUnchecked.java && java CheckedUnchecked
CheckedUnchecked.javaLesson 18 · IOException, IllegalArgumentException, finally
verified output
=== SouthBank India — Exception Handling === Parsed: ₹125,000.00 Parsed: ₹98,500.00 CSV error: Empty amount string from CSV row Parsed: ₹75,000.00 Account 1002 found at index 1 Lookup failed: Account 1005 not found Account 1003 found at index 2 finally block: Attempting DB write... Caught: Connection timeout Connection released.

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.

javac CustomException.java && java CustomException
CustomException.javaLesson 18 · InsufficientFundsException, InvalidAccountException
verified output
=== SouthBank India — Custom Exceptions === Debited ₹15,000.00 from SB-9001 | Balance: ₹15,000.00 Insufficient funds: requested ₹20,000.00 but only ₹15,000.00 available Shortfall: ₹5,000.00 Found wallet: SB-8821 Error: Account not found or frozen: XX-0000

🔌 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.

javac TryResources.java && java TryResources
TryResources.javaLesson 18 · AutoCloseable, multiple resources, reverse close order
verified output
=== SouthBank India — try-with-resources === [DB] Connected to jdbc:postgresql://localhost/southbank [DB] Query: SELECT * FROM accounts WHERE branch = 'MUMBAI' [DB] Query: UPDATE ledger SET balance = balance + 5000 WHERE id = 9001 [DB] Connection closed — jdbc:postgresql://localhost/southbank After try block — connection auto-closed [DB] Connected to jdbc:postgresql://localhost/audit [LOG] Audit log opened [DB] Query: INSERT INTO transactions VALUES (...) [LOG] TXN-4821 committed by Arjun [LOG] Audit log flushed & closed [DB] Connection closed — jdbc:postgresql://localhost/audit Both resources closed (reverse order)

📋 Exception hierarchy

TypeMust handle?Base classExamples
CheckedYes (catch or throws)ExceptionIOException, SQLException
UncheckedOptionalRuntimeExceptionNullPointerException, IllegalArgumentException
ErrorDo not catchErrorOutOfMemoryError, StackOverflowError

🧩 Mini challenge

Three exception exercises
Task 1 — Multi-catch CSV parser

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.

Task 2 — Chained exception

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.

Task 3 — AutoCloseable mock

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

EasyWhat is the difference between checked and unchecked exceptions?
+

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.

EasyWhat does 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.

MediumWhen should you define a custom exception class?
+

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.

MediumHow do you handle a checked exception inside a lambda?
+

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.

HardExplain suppressed exceptions and when they occur.
+

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

Question 1 of 5
A checked exception — what must the caller do?
Question 2 of 5
The finally block runs:
Question 3 of 5
try-with-resources calls close():
Question 4 of 5
RuntimeException is:
Question 5 of 5
Multiple resources in try-with-resources close in:
0
/ 5
Quiz complete!

Next: Spring Boot — Arc D starts here →

⚠️ Common mistakes

Catching Exception instead of specific types
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.
Empty catch block
catch (IOException e) {} silently discards the error. Always log or rethrow. An empty catch block is almost always wrong and a code smell.
Forgetting try-with-resources — relying on finally for close()
Manually closing in finally is error-prone: the close itself can throw, masking the original exception. try-with-resources handles this correctly with suppressed exceptions.
Throwing checked exceptions from lambdas
Lambda bodies can't declare 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).
  • finally always runs — use it for cleanup when not using try-with-resources.
  • try-with-resources auto-calls close() in reverse order; handles suppressed exceptions correctly.
  • Custom exceptions carry domain context; extend Exception for checked, RuntimeException for unchecked.
  • Never swallow exceptions with empty catch blocks.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →