Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lesson 10: Exception Handling — Hierarchy, try-with-resources & Custom Exceptions

Lesson 11 of 18 in the free Programming in Java notes on Siksha Sarovar, written by Rohit Jangra.

10.1 The Throwable Hierarchy

Throwable
 ├── Error                 (JVM-level, DON'T catch: OutOfMemoryError, StackOverflowError)
 └── Exception
      ├── RuntimeException (UNCHECKED: NullPointerException, ArithmeticException,
      │                     ArrayIndexOutOfBoundsException, ClassCastException,
      │                     NumberFormatException, IllegalArgumentException)
      └── everything else  (CHECKED: IOException, SQLException, FileNotFoundException,
                            InterruptedException, ClassNotFoundException)

10.2 Checked vs Unchecked — The Core Table

AspectCheckedUnchecked
Inherits fromException (minus RuntimeException)RuntimeException / Error
Compiler forces handlingYes — catch or declare (throws)No
RepresentsRecoverable external failures (file missing, network down)Programming bugs (null deref, bad index)
DetectedCompile time (the obligation)Runtime only
ExamplesIOException, SQLExceptionNullPointerException, ArithmeticException

Handle-or-declare rule: a method that can throw a checked exception must either wrap it in try/catch or declare throws IOException and push the duty to its caller.

10.3 try / catch / finally Mechanics

try {
    int r = a / b;                       // may throw ArithmeticException
} catch (ArithmeticException e) {        // most specific FIRST
    System.out.println("Divide by zero: " + e.getMessage());
} catch (RuntimeException | Error fatal) { // multi-catch (Java 7): one block, many types
    throw fatal;
} finally {
    System.out.println("finally ALWAYS runs");
}

Rules examiners probe:

  • Catch blocks are tried top-down; a superclass before its subclass is a compile error ("already been caught").
  • finally runs always — after normal completion, after a catch, even when try/catch contains return (the return value is computed first, then finally runs). It is skipped only by System.exit() or JVM death.
  • A return inside finally overrides the try's return and swallows exceptions — legal, terrible practice, favourite trick question.
  • throw raises one exception object; throws in the signature declares possible checked exceptions. Two different keywords.

10.4 try-with-resources (Java 7+)

Any AutoCloseable declared in the try header is closed automatically, in reverse order, whether or not an exception occurs — replacing the error-prone finally-close idiom:

try (var br = new java.io.BufferedReader(new java.io.FileReader("data.txt"))) {
    System.out.println(br.readLine());
}   // br.close() called for you, even on exception

If both the body and close() throw, the body's exception wins and the close failure is attached as a suppressed exception (retrievable via getSuppressed()) — an advanced-paper detail that scores full marks.

10.5 Custom Exceptions & Chaining

class InsufficientFundsException extends Exception {          // checked
    private final double shortfall;
    InsufficientFundsException(double shortfall) {
        super("Short by Rs." + shortfall);
        this.shortfall = shortfall;
    }
    double getShortfall() { return shortfall; }
}

Extend Exception for recoverable business rules, RuntimeException for precondition violations. Exception chaining preserves the root cause: throw new ServiceException("payment failed", sqlEx); — never discard the original.

10.6 Best Practices (List These for Full Marks)

  1. Catch the most specific type; never blanket-catch Exception/Throwable.
  2. Never leave a catch block empty — log or rethrow ("exception swallowing").
  3. Use try-with-resources for anything closeable.
  4. Don't use exceptions for ordinary control flow (they cost stack-trace construction).
  5. Chain causes when translating exceptions across layers.
  6. Validate early: throw IllegalArgumentException at the API boundary.

🎯 Exam Focus

  1. Draw the exception hierarchy from Throwable down. Differentiate Error and Exception.
  2. Distinguish checked and unchecked exceptions with four examples each. What is the handle-or-declare rule?
  3. Differentiate throw, throws and finally. When does finally NOT execute? What happens when both try and finally contain return?
  4. Explain try-with-resources and suppressed exceptions. Why is it superior to closing in finally?
  5. Write a program defining custom checked exception InvalidAgeException, thrown when a voter's age is below 18, handled in main.
  6. Predict the output of nested try/catch/finally blocks where an exception is thrown, caught, and a new one is thrown from finally.