Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

Java Exceptions — Complete Tutorial Notes

Table of Contents

  1. What Is an Exception?
  2. The Catch or Specify Requirement
  3. Catching and Handling Exceptions
  4. The try Block
  5. The catch Blocks
  6. The finally Block
  7. The try-with-resources Statement
  8. Putting It All Together
  9. Specifying the Exceptions Thrown by a Method
  10. How to Throw Exceptions
  11. Chained Exceptions
  12. Creating Exception Classes
  13. Unchecked Exceptions — The Controversy
  14. Advantages of Exceptions
  15. Summary
  16. Questions and Exercises

1. What Is an Exception?

An exception is an event that occurs during program execution and disrupts the normal flow of instructions.

How it works:

  • When an error happens inside a method, the method builds an exception object holding details about the error (type + program state at the time) and hands it to the Java runtime. This act is called throwing an exception.
  • After a throw, the runtime searches back through the call stack — the ordered list of methods that were invoked to reach the point of failure — looking for a block of code able to deal with that exception type. That block is an exception handler.
  • The runtime walks the stack from the method where the error occurred backwards, checking each method for a matching handler. When a matching handler is found, the exception is considered caught.
  • If no method on the stack has a suitable handler, the runtime — and therefore the whole program — terminates.

Diagrams referenced in the original page: a call-stack illustration and a "handler not found → program terminates" illustration.


2. The Catch or Specify Requirement

Java code that might throw certain exceptions must satisfy the Catch or Specify Requirement: it must either

  • be wrapped in a try block with a matching catch, or
  • live inside a method that declares the exception via a throws clause.

Code that violates this requirement fails to compile.

The Three Categories of Exceptions

Category Subject to Catch-or-Specify? Description
Checked exception Yes Anticipated, recoverable conditions (e.g., FileNotFoundException when opening a missing file). All exceptions are "checked" except Error, RuntimeException, and their subclasses.
Error No Serious conditions external to the app that it typically can't recover from (e.g., IOError from a hardware fault). Indicated by Error and its subclasses.
Runtime exception No Internal application conditions usually caused by programming bugs (e.g., NullPointerException). Indicated by RuntimeException and its subclasses.

Error + RuntimeException (and their subclasses) are collectively called unchecked exceptions.

Bypassing Catch or Specify

Some developers deliberately favor unchecked exceptions to sidestep this requirement. Oracle generally discourages this — see Unchecked Exceptions — The Controversy.


3. Catching and Handling Exceptions

This section walks through writing handlers using try, catch, and finally, using a running example class, ListOfNumbers:

// Note: This class will not compile yet.
import java.io.*;
import java.util.List;
import java.util.ArrayList;

public class ListOfNumbers {

    private List<Integer> list;
    private static final int SIZE = 10;

    public ListOfNumbers () {
        list = new ArrayList<Integer>(SIZE);
        for (int i = 0; i < SIZE; i++) {
            list.add(new Integer(i));
        }
    }

    public void writeList() {
        // The FileWriter constructor throws IOException, which must be caught.
        PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));

        for (int i = 0; i < SIZE; i++) {
            // The get(int) method throws IndexOutOfBoundsException, which must be caught.
            out.println("Value at: " + i + " = " + list.get(i));
        }
        out.close();
    }
}
  • new FileWriter(...) throws a checked IOException → compiler flags it if uncaught/unspecified.
  • list.get(i) can throw an unchecked IndexOutOfBoundsException → compiler does not flag it.

The rest of the lesson builds proper exception handling around writeList.


4. The try Block

A try block encloses the code that might throw an exception:

try {
    code
}
catch and finally blocks . . .

You can wrap each risky statement in its own try, or put multiple statements in one try with several handlers — the tutorial uses one shared try block since writeList is short:

public void writeList() {
    PrintWriter out = null;
    try {
        System.out.println("Entered try statement");
        FileWriter f = new FileWriter("OutFile.txt");
        out = new PrintWriter(f);
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    }
    catch and finally blocks  . . .
}

A catch block must immediately follow a try block to actually handle any exception it raises.


5. The catch Blocks

catch blocks are attached directly after a try block (no code allowed in between):

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}
  • ExceptionType must be (or extend) Throwable.
  • The runtime picks the first catch in source order whose type matches (or is a superclass of) the thrown object.
  • Handlers aren't limited to printing messages — they can attempt recovery, prompt the user, or re-throw via chained exceptions.

Example for writeList:

try {

} catch (IndexOutOfBoundsException e) {
    System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

Multi-catch (Java SE 7+)

A single catch clause can handle several exception types using |, reducing duplication:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Note: in a multi-catch clause, the caught variable (ex) is implicitly final — you can't reassign it inside the block.


6. The finally Block

The finally block always executes when the try exits — normally, via an exception, or via return/continue/break. This makes it the right spot for cleanup code (closing streams, releasing resources), even when you don't expect exceptions.

Caveat: finally may not run if the JVM itself exits while the try/catch code is executing.

writeList's try block can exit three ways:

  1. new FileWriter(...) throws IOException.
  2. list.get(i) throws IndexOutOfBoundsException.
  3. Everything succeeds and the block exits normally.

Regardless of which path is taken, finally runs:

finally {
    if (out != null) {
        System.out.println("Closing PrintWriter");
        out.close();
    } else {
        System.out.println("PrintWriter not open");
    }
    if (f != null) {
        System.out.println("Closing FileWriter");
        f.close();
    }
}

Important: Oracle recommends preferring try-with-resources over manual finally cleanup for closing resources:

public void writeList() throws IOException {
    try (FileWriter f = new FileWriter("OutFile.txt");
         PrintWriter out = new PrintWriter(f)) {
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    }
}

7. The try-with-resources Statement

Introduced in Java SE 7. A resource is any object implementing java.lang.AutoCloseable (which java.io.Closeable extends) that must be closed once you're done with it. The try-with-resources statement guarantees each declared resource is closed at the end of the block — regardless of normal or abrupt (exception) completion.

Basic example

static String readFirstLineFromFile(String path) throws IOException {
    try (FileReader fr = new FileReader(path);
         BufferedReader br = new BufferedReader(fr)) {
        return br.readLine();
    }
}

The old way (pre-Java 7, using finally) — and why it's risky

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
    FileReader fr = new FileReader(path);
    BufferedReader br = new BufferedReader(fr);
    try {
        return br.readLine();
    } finally {
        br.close();
        fr.close();
    }
}

If readLine() throws and br.close() in finally also throws, fr never gets closed — a resource leak, since the original exception (and the need to close fr) gets lost. With try-with-resources, closing is handled automatically and safely, in the reverse order of resource declaration.

Multiple resources

try (
    java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
    java.io.BufferedWriter writer =
        java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
    // work with zf and writer
}

Resources are closed in the opposite order of their creation (here, writer closes before zf).

try-with-resources + catch/finally

You can still attach catch/finally blocks; they execute after the declared resources are closed.

Suppressed Exceptions

If the body of the try throws and closing a resource also throws, the resource-closing exception(s) are suppressed — the exception from the try block itself is the one propagated. Suppressed exceptions can be retrieved via Throwable.getSuppressed().

AutoCloseable vs. Closeable

  • Closeable.close() throws IOException.
  • AutoCloseable.close() throws the more general Exception (or none, or a specialized subtype).
  • Closeable extends AutoCloseable.

8. Putting It All Together

Combines everything into the finished writeList method:

public void writeList() {
    PrintWriter out = null;

    try {
        System.out.println("Entering" + " try statement");

        out = new PrintWriter(new FileWriter("OutFile.txt"));
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    } catch (IndexOutOfBoundsException e) {
        System.err.println("Caught IndexOutOfBoundsException: "
                           +  e.getMessage());
    } catch (IOException e) {
        System.err.println("Caught IOException: " +  e.getMessage());
    } finally {
        if (out != null) {
            System.out.println("Closing PrintWriter");
            out.close();
        }
        else {
            System.out.println("PrintWriter not open");
        }
    }
}

Scenario 1 — an exception occurs

If FileWriter's constructor fails, it throws IOException. The runtime immediately stops the try block, searches the call stack (starting with writeList), and matches against handlers in source order. It skips the IndexOutOfBoundsException handler (type mismatch) and matches the IOException handler. After the catch block runs, finally executes (the PrintWriter was never opened, so nothing to close). Output:

Entering try statement
Caught IOException: OutFile.txt
PrintWriter not open

Scenario 2 — the try block exits normally

All statements succeed; control falls through to finally, which closes the open PrintWriter. Output:

Entering try statement
Closing PrintWriter

9. Specifying the Exceptions Thrown by a Method

Instead of catching a checked exception locally, a method can declare it using a throws clause, letting a caller further up the stack deal with it. This is useful when a method (e.g., part of a reusable library) can't anticipate how every caller wants errors handled.

Original (won't compile):

public void writeList() {
    PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
    for (int i = 0; i < SIZE; i++) {
        out.println("Value at: " + i + " = " + list.get(i));
    }
    out.close();
}

Fixed by declaring the checked exception:

public void writeList() throws IOException, IndexOutOfBoundsException {

Since IndexOutOfBoundsException is unchecked, including it is optional:

public void writeList() throws IOException {

10. How to Throw Exceptions

Any code — yours, a library's, or the JVM's — can throw an exception, always via the throw statement:

throw someThrowableObject;

Example — a stack's pop() throwing when empty:

public Object pop() {
    Object obj;

    if (size == 0) {
        throw new EmptyStackException();
    }

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}

EmptyStackException is unchecked, so pop() needs no throws clause.

The Throwable hierarchy

All exception types descend from Throwable, which has two direct children:

  • Error — Serious JVM-level failures (e.g., dynamic linking failure). Simple programs typically don't catch or throw these.
  • Exception — Ordinary application problems. Most code throws/catches Exception subclasses rather than Error.
    • RuntimeException (a subclass of Exception) — reserved for API-misuse style problems, e.g. NullPointerException. Discussed further in section 13.

Referenced figure: class hierarchy diagram of Throwable → Error / Exception → RuntimeException, etc.


11. Chained Exceptions

An app often reacts to one exception by throwing another — the first causes the second. Chained exceptions preserve that causal link.

Relevant Throwable API:

Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)

Example:

try {

} catch (IOException e) {
    throw new SampleException("Other IOException", e);
}

Here, catching an IOException creates a new SampleException that records the original as its cause, then re-throws up the stack.

Accessing Stack Trace Info

catch (Exception cause) {
    StackTraceElement elements[] = cause.getStackTrace();
    for (int i = 0, n = elements.length; i < n; i++) {
        System.err.println(elements[i].getFileName()
            + ":" + elements[i].getLineNumber()
            + ">> "
            + elements[i].getMethodName() + "()");
    }
}

A stack trace documents the execution history of the current thread up to the point the exception was thrown — a key debugging tool.

Logging API

Rather than manually formatting/printing a trace, you can route it through java.util.logging:

try {
    Handler handler = new FileHandler("OutFile.log");
    Logger.getLogger("").addHandler(handler);

} catch (IOException e) {
    Logger logger = Logger.getLogger("package.name");
    StackTraceElement elements[] = e.getStackTrace();
    for (int i = 0, n = elements.length; i < n; i++) {
        logger.log(Level.WARNING, elements[i].getMethodName());
    }
}

12. Creating Exception Classes

Consider writing your own exception type when any of these apply:

  • The Java platform has no exception type that fits your case.
  • You want users to be able to distinguish your exceptions from other vendors'.
  • Your code can throw more than one related exception (grouping helps).
  • Your package should be self-contained rather than depending on someone else's exception types.

Example: a linked-list package

A linked list with methods like objectAt(int), firstObject(), and indexOf(Object) might throw several related error conditions. Bundling a custom exception hierarchy (e.g. a LinkedListException with subclasses) lets callers catch them all with one handler and keeps the package self-contained.

Referenced figure: a sample class hierarchy for such linked-list exceptions.

Choosing a Superclass

  • Extend Exception for ordinary application-level problems (the common case).
  • Reserve Error for serious, hard system failures — not typical for application exception classes.

Convention: append Exception to the class name of anything that (directly or indirectly) extends Exception, for readability.


13. Unchecked Exceptions — The Controversy

Because RuntimeException, Error, and their subclasses are exempt from the Catch-or-Specify rule, it's tempting to make everything unchecked just to avoid throws clauses and compiler friction. Oracle argues against this shortcut.

Why checked exceptions exist: any checked exception a method can throw is effectively part of its public API — callers need visibility into it to decide how to react, just like parameters or a return type.

Why runtime exceptions are exempt: they typically signal programming bugs (e.g., division by zero, null dereferences, bad array indices) that calling code generally can't meaningfully recover from. They can occur almost anywhere, so requiring throws declarations for all of them would clutter every method signature and hurt readability.

A common legitimate use of RuntimeException: validating that a caller used your API correctly, e.g., throwing NullPointerException when a required argument is null.

Guideline given by Oracle:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Don't just make something a RuntimeException because you're annoyed by having to declare it.


14. Advantages of Exceptions

Advantage 1 — Separates error-handling from main logic

Without exceptions, error checking clutters the "real" logic with nested conditionals (illustrated via a pseudocode readFile function whose main 7 lines balloon into a tangle of if/errorCode checks). Exceptions let you write the happy path plainly and isolate error handling into catch blocks:

readFile {
    try {
        open the file;
        determine its size;
        allocate that much memory;
        read the file into memory;
        close the file;
    } catch (fileOpenFailed) {
       doSomething;
    } catch (sizeDeterminationFailed) {
        doSomething;
    } catch (memoryAllocationFailed) {
        doSomething;
    } catch (readFailed) {
        doSomething;
    } catch (fileCloseFailed) {
        doSomething;
    }
}

(Exceptions don't eliminate the work of handling errors — they just organize it more clearly.)

Advantage 2 — Propagating errors up the call stack

With traditional error codes, every intermediate method (method2, method3, ...) must manually check and re-return error codes even if it doesn't care about them, just to relay the error to the one method (method1) that does. With exceptions, intermediate methods can simply declare throws and let the exception propagate automatically:

method1 {
    try {
        call method2;
    } catch (exception e) {
        doErrorProcessing;
    }
}

method2 throws exception {
    call method3;
}

method3 throws exception {
    call readFile;
}

Advantage 3 — Grouping and differentiating error types

Since exceptions are objects, they naturally form a class hierarchy. java.io.IOException and its many subclasses (e.g. FileNotFoundException) let you:

  • catch a very specific error type:
    catch (FileNotFoundException e) { ... }
  • or catch broadly by superclass:
    catch (IOException e) { ... }
  • or catch almost everything with catch (Exception e) — generally discouraged except for simple "log and exit" scenarios, since overly broad handlers can mask unanticipated problems.

Best practice: keep handlers as specific as reasonably possible.


15. Summary

  • Use throw with a Throwable-descended object to signal an error.
  • A method with an uncaught checked exception must declare it via throws.
  • Catch exceptions with try / catch / finally:
    • try — marks code that might fail.
    • catch — handles a specific exception type.
    • finally — always runs; ideal for cleanup (closing files, releasing resources).
  • A try statement needs at least one catch or a finally (or both), and may have multiple catch blocks.
  • Exception chaining lets one exception reference the exception that caused it, forming a cause chain.

16. Questions and Exercises

The tutorial ends with self-check questions and two coding exercises (answers linked separately on Oracle's site):

Questions (paraphrased):

  1. Is a bare try { } finally { } (no catch) legal Java?
  2. What can catch (Exception e) { } catch, and what's the downside of writing a handler that broad?
  3. Does a try block followed by catch (Exception e) then catch (ArithmeticException a) compile? Why or why not?
  4. Match scenarios (array index out of bounds; JVM unable to find platform classes at startup; reaching end-of-stream; reading past end-of-stream after closing) to outcomes (error / checked exception / compile error / no exception).

Exercises:

  1. Add a readList method to ListOfNumbers.java that reads int values from a file, prints each, and appends them to the list — catching all appropriate exceptions.
  2. Fix a cat(File file) method (using RandomAccessFile) so that it compiles, given it currently lacks required exception handling around a finally block.

Answers are provided on Oracle's companion page (QandE/answers.html).


Quick Reference Cheat Sheet

Concept Keyword / Type Notes
Try block try { } Wraps risky code
Handler catch (Type e) { } Matched in source order; first assignable match wins
Multi-catch catch (A|B e) { } Java 7+; e is implicitly final
Cleanup finally { } Always runs (except JVM exit mid-try)
Auto-cleanup try (Resource r = ...) { } Java 7+; resource must implement AutoCloseable
Declare throws Type Required for uncaught checked exceptions
Raise throw new Type(...) Argument must be a Throwable
Chain new Ex(msg, cause) / initCause() / getCause() Preserves original cause
Base classes Throwable → Error / Exception → RuntimeException RuntimeException/Error = unchecked

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors