Java Tutorial chapters (15)
  1. 01Java Introduction
  2. 02Java Variables & Data Types
  3. 03Java Control Statements
  4. 04Java OOPs Basics
  5. 05Java Inheritance & Polymorphism
  6. 06Java Abstraction & Interfaces
  7. 07Java Strings
  8. 08Java Arrays
  9. 09Java Exception Handling
  10. 10Java Collections Framework
  11. 11Java Multithreading
  12. 12Java 8 Features
  13. 13Java I/O & File Handling
  14. 14Java JDBC
  15. 15Java MCQ

Chapter 09

Java Exception Handling

5 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

An exception is an event that disrupts normal program flow.

Java handles it with try, catch, finally, throw and throws.

This chapter also covers custom exceptions and the difference between checked and unchecked exceptions.

Real programs must survive bad input, missing files and network failures.

Exception handling is a top interview and viva topic.

Validating user input, handling database or file errors, returning meaningful API error responses and cleaning up resources.

1

Exception Handling in Java

Exception handling is the mechanism of detecting a run-time error (an exception object), transferring control to a handler and letting the program continue or end gracefully. All exceptions are objects of classes that extend java.lang.Throwable.

In short: When something goes wrong, Java throws an exception like a flare. If a catch block catches it, the program recovers; otherwise the program stops with a stack trace.

Think about it

Without handling, one bad input crashes the application. Exceptions separate normal logic from error logic and keep code readable. An ATM: if the card is invalid it shows a message and returns the card instead of shutting down the whole machine.

Hierarchy: Object → Throwable → {Error, Exception}.

Error (OutOfMemoryError, StackOverflowError) represents serious JVM problems that programs should not normally catch.

Exception splits into checked exceptions (IOException, SQLException) and RuntimeException with its unchecked subclasses (ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, ClassCastException).

When an exception occurs, the JVM creates an exception object, looks for a matching catch in the current method and, if none exists, unwinds the call stack to the caller, and so on until main; then the default handler prints the stack trace and ends the thread.

Useful methods: getMessage(), getCause(), printStackTrace(), getStackTrace().

Handle only what you can recover from, never swallow exceptions silently, and catch the most specific type first.

Key points

  • Throwable: Root class of everything that can be thrown.
  • Error: Serious JVM-level problem; usually not caught.
  • Stack trace: List of method calls active when the exception was created.
  • Handler: A catch block that processes a matching exception.
  • Five keywords: try, catch, finally, throw, throws.
  • ArithmeticException: integer divide by zero (double division gives Infinity, no exception).
  • NullPointerException: using a null reference. NumberFormatException: bad parseInt text.
  • Specific catch blocks must come before general ones.

Example

Code
Catching common run-time exceptions:
public class ExceptionBasics {
    public static void main(String[] args) {
        try {
            int a = 10, b = 0;
            System.out.println(a / b);           // ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Caught: " + e.getMessage());   // Caught: / by zero
        }

        System.out.println(10.0 / 0);            // Infinity (no exception)

        try {
            String s = null;
            System.out.println(s.length());      // NullPointerException
        } catch (NullPointerException e) {
            System.out.println("Null reference");
        }

        try {
            Integer.parseInt("12ab");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());  // For input string: "12ab"
        }

        // Multi-catch (Java 7)
        try {
            int[] arr = new int[2];
            arr[2] = 5;
        } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
            System.out.println("Problem: " + e.getClass().getSimpleName());
        }

        System.out.println("Program continues");
    }
}
2

try-catch-finally in Java

try holds code that may throw; catch handles a specific exception type; finally holds cleanup code that runs whether or not an exception occurred. A try must be followed by at least one catch or a finally (or be a try-with-resources).

In short: try = attempt, catch = rescue plan, finally = always clean up, even if you leave early.

Think about it

Resources such as files, sockets and DB connections must be closed even when errors occur; finally and try-with-resources guarantee that. Switching off the stove after cooking whether the dish was a success or a disaster.

Execution: if no exception occurs, catch is skipped and finally runs.

If an exception matches a catch, that catch runs, then finally.

If nothing matches, finally still runs and the exception continues up.

Catch blocks are checked top to bottom, so a subclass catch placed after its superclass catch is a compile error.

finally does NOT run only if the JVM exits (System.

exit, crash) or the thread is killed.

A `return` inside try still runs finally first; but the returned value was already evaluated (so changing a primitive in finally does not change it).

A `return` inside finally overrides any earlier return or exception, which is considered bad practice.

try-with-resources (Java 7) automatically calls close() on any AutoCloseable declared in the parentheses, in reverse order, replacing most finally cleanup.

Nested try blocks are allowed.

Key points

  • finally: Block that always executes after try/catch (except JVM exit).
  • Multi-catch: catch (A | B e) handles unrelated types in one block.
  • try-with-resources: try (Resource r = ...) closes r automatically.
  • Suppressed exception: Exception from close() recorded when the try block already threw.
  • Order: try → matching catch → finally.
  • catch(Exception e) must be after more specific catches.
  • return in finally overrides return in try.
  • System.exit(0) in try prevents finally from running.

Example

Code
try, catch, finally and try-with-resources:
public class FinallyDemo {
    static int f1() {
        try {
            return 1;
        } finally {
            System.out.println("finally runs");   // printed before 1 is returned
        }
    }

    @SuppressWarnings("finally")
    static int f2() {
        try {
            return 1;
        } finally {
            return 2;                              // overrides: returns 2
        }
    }

    static int f3() {
        int x = 10;
        try {
            return x;                              // value 10 is saved
        } finally {
            x++;                                   // does not change returned value
        }
    }

    static class Res implements AutoCloseable {
        private final String name;
        Res(String name) { this.name = name; System.out.println("open " + name); }
        public void close() { System.out.println("close " + name); }
    }

    public static void main(String[] args) {
        System.out.println(f1());   // finally runs, then 1
        System.out.println(f2());   // 2
        System.out.println(f3());   // 10

        try {
            System.out.println("try");
            Object o = "text";
            Integer i = (Integer) o;               // ClassCastException
        } catch (ClassCastException e) {
            System.out.println("catch");
        } finally {
            System.out.println("finally");
        }
        // try, catch, finally

        try (Res a = new Res("A"); Res b = new Res("B")) {
            System.out.println("working");
        }
        // open A, open B, working, close B, close A
    }
}
3

throw and throws in Java

throw is a statement used inside a method to actually raise one exception object (throw new IllegalArgumentException("x")). throws is a clause in the method signature that declares which checked exceptions the method may pass on to its caller.

In short: throw = I am throwing the ball now. throws = warning label: this method may throw the ball at you.

Think about it

Methods must be able to report errors to their callers; throw raises them and throws warns the compiler and the caller. A cashier raises an alert (throw) when a note is fake; the shop policy (throws) says the cashier may raise such alerts.

throw takes exactly one Throwable instance and ends the current flow like return.

throws can list several exception types separated by commas and is mandatory for checked exceptions that a method does not handle itself; for unchecked exceptions it is optional documentation.

A caller must either catch or declare every checked exception it calls.

When overriding, a method cannot declare broader checked exceptions than the parent method.

You may rethrow a caught exception (throw e;) or wrap it into another exception keeping the original as the cause (throw new ServiceException("msg", e)) — this is called exception chaining and preserves the root cause in the stack trace.

Use throw for validation (null checks, range checks) at the start of a method (fail fast).

Key points

Example

Code
throw, throws and exception chaining:
import java.io.*;

public class ThrowDemo {
    static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Not eligible to vote: " + age);
        }
        System.out.println("Eligible");
    }

    // Checked exception must be declared (or caught)
    static void readFile(String path) throws FileNotFoundException {
        if (!new File(path).exists()) {
            throw new FileNotFoundException("Missing: " + path);
        }
    }

    static void service() throws Exception {
        try {
            readFile("nofile.txt");
        } catch (FileNotFoundException e) {
            throw new Exception("Service failed", e);    // chaining
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(20);                                // Eligible
            checkAge(15);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());          // Not eligible to vote: 15
        }

        try {
            service();
        } catch (Exception e) {
            System.out.println(e.getMessage());          // Service failed
            System.out.println(e.getCause().getMessage());// Missing: nofile.txt
        }
    }
}
4

Custom Exception in Java

A custom (user-defined) exception is a class you create by extending Exception (checked) or RuntimeException (unchecked) to represent an error specific to your application domain.

In short: If Java has no exception that describes your problem well, make your own, for example InsufficientBalanceException.

Try → catch errors safely

Think about it

Domain-specific error types make code self-documenting and allow precise catch blocks. A bank app throws InsufficientBalanceException instead of a vague RuntimeException.

Extend Exception when the caller can reasonably recover and the compiler should force handling; extend RuntimeException for programming errors or when forcing try/catch would be noise.

Provide constructors: no-arg, (String message), (String message, Throwable cause).

Add extra fields (error code, amount) with getters when handlers need details.

Name the class with the suffix Exception.

Add a serialVersionUID if you want to avoid a compiler warning because Throwable is Serializable.

Keep the hierarchy small: one base exception per module with a few subclasses.

Custom exceptions make logs readable, allow different handling per error and keep low-level exceptions (SQLException) from leaking into upper layers.

Key points

Example

Code
Checked and unchecked custom exceptions:
class InsufficientBalanceException extends Exception {
    private final double shortfall;

    public InsufficientBalanceException(String message, double shortfall) {
        super(message);
        this.shortfall = shortfall;
    }
    public double getShortfall() { return shortfall; }
}

class InvalidAmountException extends RuntimeException {   // unchecked
    public InvalidAmountException(String message) { super(message); }
}

class Account {
    private double balance;
    Account(double balance) { this.balance = balance; }

    void withdraw(double amount) throws InsufficientBalanceException {
        if (amount <= 0) {
            throw new InvalidAmountException("Amount must be positive");
        }
        if (amount > balance) {
            throw new InsufficientBalanceException("Insufficient balance", amount - balance);
        }
        balance -= amount;
        System.out.println("Withdrawn " + amount + ", left " + balance);
    }
}

public class CustomExceptionDemo {
    public static void main(String[] args) {
        Account acc = new Account(1000);
        try {
            acc.withdraw(400);                 // Withdrawn 400.0, left 600.0
            acc.withdraw(900);
        } catch (InsufficientBalanceException e) {
            System.out.println(e.getMessage() + ", short by " + e.getShortfall()); // short by 300.0
        }
        try {
            acc.withdraw(-5);
        } catch (InvalidAmountException | InsufficientBalanceException e) {
            System.out.println(e.getMessage());   // Amount must be positive
        }
    }
}
5

Checked vs Unchecked Exceptions

Checked exceptions are subclasses of Exception (excluding RuntimeException) that the compiler forces you to catch or declare. Unchecked exceptions are subclasses of RuntimeException (and Error) that the compiler does not check.

In short: Checked = the compiler makes you prepare for it. Unchecked = it can happen anywhere and Java does not force you.

Checked must handle · Unchecked may crash

Think about it

The distinction decides what the compiler forces you to write, and it is asked in almost every Java interview. Checked: a flight may be delayed, so the airline forces you to plan. Unchecked: you forgot your passport — your own mistake.

Checked examples: IOException, FileNotFoundException, SQLException, ClassNotFoundException, InterruptedException.

They usually come from the outside world (files, network, database) and the caller can often recover (retry, ask for another file).

Unchecked examples: NullPointerException, ArithmeticException, IllegalArgumentException, IndexOutOfBoundsException, ClassCastException — mostly caused by programming mistakes that should be fixed in code, not caught.

Errors (OutOfMemoryError, StackOverflowError) are also unchecked.

The compiler gives "unreported exception X; must be caught or declared to be thrown" for a missing checked-exception handler.

Modern frameworks (Spring) prefer unchecked exceptions to avoid boilerplate.

Lambdas cannot throw checked exceptions through standard functional interfaces without wrapping.

Key points

  • Checked: Verified at compile time: catch or declare.
  • Unchecked: RuntimeException and Error; not verified by the compiler.
  • Recoverable: Situation where the program can reasonably continue.
  • Checked = Exception but not RuntimeException. Unchecked = RuntimeException + Error.
  • Checked: IOException, SQLException, InterruptedException, ClassNotFoundException.
  • Unchecked: NPE, ArithmeticException, ArrayIndexOutOfBounds, NumberFormatException, ClassCastException.
  • Handle checked with try/catch or throws; fix unchecked by writing correct code.

Example

Code
Checked, unchecked and Error:
import java.io.*;

public class CheckedVsUnchecked {
    public static void main(String[] args) {
        // CHECKED: compile error if neither caught nor declared
        try {
            Thread.sleep(100);                    // InterruptedException
            new FileReader("missing.txt").close();// FileNotFoundException (IOException)
        } catch (InterruptedException | IOException e) {
            System.out.println("Checked: " + e.getClass().getSimpleName());
            // Checked: FileNotFoundException
        }

        // UNCHECKED: compiles without any try/catch
        int[] data = {1, 2, 3};
        try {
            System.out.println(data[3]);          // ArrayIndexOutOfBoundsException
        } catch (RuntimeException e) {
            System.out.println("Unchecked: " + e.getClass().getSimpleName());
        }

        // Error: do not catch normally
        try {
            recurse(1);
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError caught");
        }
    }

    static void recurse(int n) { recurse(n + 1); }
}

Solved examples

Example 01 · Basic

Predict the output order: try { print("A"); int x = 5 / 0; print("B"); } catch (ArithmeticException e) { print("C"); } finally { print("D"); } print("E");

Given Data:
    Required To Find:

    Printed sequence

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: A prints
    Step 2: Division throws, so B is skipped
    Step 3: catch prints C
    Step 4: finally prints D
    Step 5: Program continues with E
    Final Answer: A C D E

    Approach note: Statements after the exception point inside try are skipped.

    Example 02 · Intermediate

    What does f() return? static int f() { try { return 1; } finally { return 2; } }

    Given Data:
      Required To Find:

      Returned value

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: try wants to return 1
      Step 2: finally executes before the method really returns
      Step 3: return 2 in finally replaces the earlier return
      Final Answer: 2

      Approach note: Never return from finally in real code; it hides exceptions.

      Example 03 · Intermediate

      Create a custom checked exception AgeException and throw it when age < 18.

      Given Data:
        Required To Find:

        Class and usage

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: class AgeException extends Exception with a String constructor calling super(msg)
        Step 2: Method void vote(int age) throws AgeException
        Step 3: if (age < 18) throw new AgeException("Underage")
        Step 4: Call vote inside try/catch
        Final Answer: Catch prints "Underage" for age 15.

        Approach note: Checked exceptions require throws in the signature.

        Example 04 · Basic

        What is printed? try { int x = Integer.parseInt("12a"); } catch (NumberFormatException e) { System.out.println("bad"); } finally { System.out.println("end"); }

        Given Data:
          Required To Find:

          Output

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: parseInt("12a") throws NumberFormatException
          Step 2: catch prints bad
          Step 3: finally always prints end
          Final Answer: bad end

          Approach note: finally runs whether or not an exception was caught.

          Real-world applications

          Java

          Using Java Exception Handling in real projects

          Validating user input, handling database or file errors, returning meaningful API error responses and cleaning up resources.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: finally always runs, no matter what.

          Why this is wrong: System.exit() or a JVM crash stops the program before finally.

          ✅ Verified Truth: finally runs after try/catch in normal and exceptional flow, except when the JVM stops.

          ⚠️ Exam Tip: Examiners love System.exit inside try.

          ❌ Myth: throw and throws are the same.

          Why this is wrong: throw raises one object; throws is a declaration in the signature.

          ✅ Verified Truth: throw is a statement, throws is a clause.

          ⚠️ Exam Tip: Say "throw inside, throws outside".

          ❌ Myth: All exceptions must be caught or declared.

          Why this is wrong: Only checked exceptions are enforced by the compiler.

          ✅ Verified Truth: Unchecked exceptions and Errors need no handling.

          ⚠️ Exam Tip: RuntimeException subclasses are unchecked.

          ❌ Myth: Dividing a double by zero throws ArithmeticException.

          Why this is wrong: Floating-point division follows IEEE 754.

          ✅ Verified Truth: It gives Infinity or NaN; only integer division throws.

          ⚠️ Exam Tip: 5 / 0 throws, 5.0 / 0 gives Infinity.

          Revision notes

          An exception is an event that disrupts normal program flow. Java handles it with try, catch, finally, throw and throws. This chapter also covers custom exceptions and the difference between checked and unchecked exceptions.

          High-Yield Quick Revision Points

          1. Throwable → Error / Exception → RuntimeException
          2. try needs catch or finally; catch specific before general
          3. finally runs always except System.exit; return in finally overrides
          4. throw = raise one object; throws = declare in signature
          5. Custom: extends Exception (checked) or RuntimeException (unchecked)
          6. Checked = compile-time enforced; Unchecked = RuntimeException + Error

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which is the root class of all exceptions and errors?

          Question 2 · MCQ (Interview / semester)

          Which one is a checked exception?

          Question 3 · MCQ (Interview / semester)

          Which block always executes (normal flow)?

          Question 4 · MCQ (Interview / semester)

          Which keyword declares exceptions in a method signature?

          Question 5 · MCQ (Interview / semester)

          What is the output of System.out.println(10 / 0)?

          Question 6 · MCQ (Interview / semester)

          To create a custom checked exception you extend: