Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Exception handling in Java

Practical, exam-focused notes on Java exception handling: definitions, propagation, syntax, examples (including custom and try-with-resources), common mistakes and sample questions.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Exception handling lets a Java program detect and respond to unexpected problems (I/O failure, bad input, arithmetic errors) without crashing. Engineers use it in server code, file I/O, concurrent systems, and user interfaces to keep services running, free resources, and give meaningful messages or retries.

Key ideas

Start from first principles and clear definitions.

  • "Throwable": a class in the Java API (java.lang.Throwable) that is the root of the Java exception hierarchy. Every throwable value is an object of a class that extends Throwable.

  • "Exception": a subclass of Throwable (java.lang.Exception). It represents conditions that programs might want to catch.

  • "Error": a subclass of Throwable (java.lang.Error) used for serious problems from the JVM (e.g., OutOfMemoryError). Program code should not normally catch Errors.

  • "Checked exception": an exception whose class is a subclass of Exception but not a subclass of RuntimeException. The Java compiler requires that a method either catches such exceptions or declares them in its throws clause.

  • "Unchecked exception": an exception whose class is a subclass of RuntimeException (or Error). The compiler does not require methods to declare or catch them. Examples: NullPointerException, ArithmeticException.

  • "throw": a Java statement used to raise a throwable object explicitly. Example: throw new IOException("msg");.

  • "throws": part of a method (or constructor) signature that declares which checked exceptions it may throw, letting callers know they must handle or declare them. When overriding a method, you cannot declare new or broader checked exceptions than the overridden method; you may declare the same or narrower checked exceptions (unchecked exceptions are unaffected).

  • "try, catch, finally": blocks used to run code that may throw exceptions (try), handle specific exceptions (catch), and run cleanup code that should always execute (finally). The finally block runs whether the try completed normally or abruptly (by return or exception), except in a couple of extreme cases such as JVM termination by System.exit.

  • Exception propagation: when an exception is thrown inside a method and not caught there, it propagates (moves) to the caller. If the caller does not catch it, the exception continues propagating up the call stack until caught or until it reaches the JVM default handler, which prints a stack trace and terminates that thread; if uncaught on the main thread, the program terminates.

  • To draw the usual propagation diagram in an answer: draw 3 vertical stacked rectangles labelled from top (caller main) to bottom (deep method). Put the throw point in the lowest rectangle and an arrow from that rectangle to the first rectangle up the stack that has a matching catch. Label arrows "propagate". If caught, draw a catch block attached to that caller frame.

  • Try-with-resources: syntax introduced in Java 7 to automatically close resources that implement AutoCloseable. Resources are closed automatically when the try block completes, in reverse order of initialization and before any catch or finally blocks run. If resource closing throws an exception during stack unwinding, such exceptions are recorded as suppressed exceptions on the primary exception. Since Java 9, you can also specify effectively final variables in the resource list.

  • Suppressed exceptions and chaining: Java stores suppressed exceptions on the primary Throwable (Throwable.addSuppressed). Exception chaining is storing the cause of an exception (new Exception("msg", cause) or Throwable.initCause).

  • Catch order rule: a catch clause that handles a superclass exception must come after any catch that handles its subclasses. Otherwise the subclass catch is unreachable and the compiler errors. In a multi-catch, the alternatives must be disjoint (no subtype/supertype relationships).

  • Best practices: do not catch Throwable or Error unless you have a very good reason; prefer small try blocks; close resources (use try-with-resources); avoid using exceptions for normal control flow; include useful messages and preserve the cause when rethrowing (new MyException(msg, cause)); never return from or throw new exceptions in a finally block because it can mask the original exception.

Formulas

Java syntax lines to remember (one per line):

try { /* code that may throw */ } catch (ExceptionType e) { /* handle */ } finally { /* always run */ }

try { ... } catch (Type1 | Type2 e) { ... } // multi-catch; the catch parameter e is implicitly final (cannot be assigned)

throw new ExceptionType("message"); // raise an exception object

void m() throws IOException, MyCheckedException { /* may throw checked exceptions */ } // method declaration

class MyException extends Exception { public MyException(String msg) { super(msg); } } // custom checked exception

try (Resource r = new Resource()) { /* r automatically closed */ } // Resource implements AutoCloseable try (A a = ...; B b = ...) { ... } // a and b are closed automatically in reverse order

new Exception("message", cause) // create exception with cause (exception chaining)

e.addSuppressed(other) // adds suppressed exception to e (used by try-with-resources)

Worked examples

Example 1: division with catch and finally (reads two integers from stdin)

Code (save as DivisionExample.java and run):

class DivisionExample {
    public static void main(String[] args) {
        java.util.Scanner sc = new java.util.Scanner(System.in);
        System.out.println("Enter numerator and denominator:");
        int a = sc.nextInt();
        int b = sc.nextInt();
        try {
            int r = divide(a, b);
            System.out.println("Result: " + r);
        } catch (ArithmeticException e) {
            System.out.println("Caught: " + e.getClass().getName() + ": " + e.getMessage());
        } finally {
            sc.close();
            System.out.println("Finally executed");
        }
    }
    static int divide(int x, int y) {
        return x / y; // may throw ArithmeticException if y == 0
    }
}

Sample input:

10 0

Exact output:

Enter numerator and denominator: Caught: java.lang.ArithmeticException: / by zero Finally executed

Example 2: try-with-resources and a custom checked exception (save as PositiveCheck.java)

class PositiveCheck {
    static class NegativeNumberException extends Exception {
        public NegativeNumberException(String msg) { super(msg); }
    }

    public static void main(String[] args) {
        try (java.util.Scanner sc = new java.util.Scanner(System.in)) {
            System.out.println("Enter a positive integer:");
            int n = sc.nextInt();
            checkPositive(n);
            System.out.println("You entered " + n);
        } catch (NegativeNumberException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
    }

    static void checkPositive(int x) throws NegativeNumberException {
        if (x < 0) throw new NegativeNumberException("negative: " + x);
    }
}

Sample input 1:

-5

Exact output 1:

Enter a positive integer: Caught custom exception: negative: -5

Sample input 2:

10

Exact output 2:

Enter a positive integer: You entered 10

Notes: these programs are minimal and meant for exams. In production code you would validate input and handle InputMismatchException.

Common mistakes

  • Forgetting to close resources when not using try-with-resources (leads to resource leak).
  • Swallowing exceptions by catching and doing nothing or only printing stack trace without handling or rethrowing.
  • Declaring throws for unchecked exceptions unnecessarily.
  • Using exceptions for normal control flow instead of normal condition tests.
  • Assuming finally always runs even after System.exit (System.exit terminates JVM so finally may not run).

For your exam

Question types you will see: definitions (give clear definitions of Throwable, Exception, Error, checked/unchecked), short notes (try-with-resources, suppression), code-tracing (what prints for given program), write code (create custom exception, use throws), and diagrams (draw stack and show propagation).

What a full-marks answer includes:

  • Precise definitions (bold terms explained),
  • Correct syntax and short code example where required,
  • For propagation questions: a neat labelled stack diagram and step-by-step explanation of how control moves,
  • For programs: input, output and explanation of why each line printed,
  • Mention of relevant Java version if feature is recent (e.g., try-with-resources Java 7+).

Quick check

  1. What is the difference between a checked and an unchecked exception?
  2. What does the throws clause in a method signature do?
  3. When are suppressed exceptions created (one sentence)?

Answers: 1) Checked exceptions are subclasses of Exception but not RuntimeException and must be declared or caught; unchecked are subclasses of RuntimeException (or Error) and need not be declared. 2) It declares which checked exceptions the method may throw so callers must handle or declare them. 3) Suppressed exceptions are created when try-with-resources is closing resources and those close() calls throw exceptions while another exception is already being thrown; the close() exceptions become suppressed on the primary exception.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?