Java
Module 14: Exception HandlingBeginner28 min read

Exceptions, Try-Catch-Finally & Try-With-Resources

Handle runtime failures gracefully using try-catch, multi-catch, try-with-resources (AutoCloseable), custom exceptions, and best practices.

Key Takeaways & Core Concepts
  • `Error`: Severe JVM/system failures (OutOfMemoryError, StackOverflowError, NoClassDefFoundError). Applications generally cannot recover from these and should not catch them.
  • `Exception`: Checked Exceptions (`IOException`, `SQLException`, `ClassNotFoundException`): Verified at compile time; the caller must* either handle them with try-catch or declare throws in the method signature.

Introduction

In production software, failures are inevitable: network timeouts, missing files, invalid user input, and database deadlocks. Java's exception handling architecture separates normal business logic from error recovery, ensuring resources are never leaked and failures propagate with rich diagnostic stack traces.

Custom Checked Exception & Try-Catch-Finally
1class InsufficientFundsException extends Exception {
2 InsufficientFundsException(String msg) { super(msg); }
3}
4
5public class Main {
6 static void withdraw(double balance, double amount) throws InsufficientFundsException {
7 if (amount > balance) {
8 throw new InsufficientFundsException("Requested " + amount + " exceeds balance " + balance);
9 }
10 System.out.println("Withdrawn: " + amount);
11 }
12
13 public static void main(String[] args) {
14 try {
15 withdraw(1000, 1500);
16 } catch (InsufficientFundsException e) {
17 System.out.println("Caught: " + e.getMessage());
18 } finally {
19 System.out.println("Transaction audit logged.");
20 }
21 }
22}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
22 lines
Note: Extending `Exception` creates a checked exception, forcing callers to handle insufficient-balance scenarios explicitly.

Exception Hierarchy

Every throwable object inherits from java.lang.Throwable, which splits into two distinct branches:

  • `Error`: Severe JVM/system failures (OutOfMemoryError, StackOverflowError, NoClassDefFoundError). Applications generally cannot recover from these and should not catch them.
  • `Exception`:
  • Checked Exceptions (IOException, SQLException, ClassNotFoundException): Verified at compile time; the caller must either handle them with try-catch or declare throws in the method signature.
  • Unchecked Exceptions (RuntimeException subclasses such as NullPointerException, IllegalArgumentException, ArithmeticException, IndexOutOfBoundsException): Not checked at compile time; usually indicate programming bugs or violated preconditions.

How Exception Propagation & Call Stack Unwinding Work

When an exception is thrown inside a method, the JVM halts normal execution and searches the current method's exception table for a matching catch block. If none exists, the JVM pops the current stack frame and repeats the search in the caller method (exception propagation) until a handler is found or the thread terminates.

Try-With-Resources (Java 7+)

Before Java 7, closing files or database connections required verbose finally blocks that could mask the original exception if close() itself threw an error. Try-with-resources (try (var res = ...) { ... }) automatically closes any AutoCloseable resource in reverse declaration order and preserves suppressed exceptions cleanly via getSuppressed().

final vs finally vs finalize

Keyword / MethodRole
finalPrevents variable reassignment, method overriding, or class inheritance
finallyBlock that always executes after try/catch (unless System.exit() or JVM crash)
finalize()Deprecated GC cleanup hook; never rely on it—use AutoCloseable instead

Common Mistakes & Best Practices

  • Never write empty catch (Exception e) {} blocks that silently hide bugs.
  • Always catch most-specific exceptions before broader ones (e.g., FileNotFoundException before IOException).
  • Never use exceptions for normal control flow (like exiting a loop)—stack trace capture is expensive.
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)