Exception Handling · Introduction to Java Programming

Re-throwing an Exception

Watch lectures

Re-throwing an Exception

1. What Is Re-throw? (beginner)

Catch → log/cleanup → throw SAME (or new) up! Low layer adds context ("which file?"), high layer decides (retry/abort). Like clerk stamps + forwards file upward!

2. Code — Add Context + Forward!

static void read(String f) throws IOException {
    try {
        new BufferedReader(new FileReader(f)).readLine();
    } catch (FileNotFoundException e) {
        System.out.println("log: missing " + f); // low: log!
        throw e; // SAME forward! (re-throw!)
        // throw new IOException("config " + f + " missing", e); // WRAP with cause! (better!)
    }
}
public static void main(String[] args) {
    try { read("a.txt"); }
    catch (IOException e) { System.out.println("high: abort!"); }
}

3. Rules (traps!)

  • throw e; keeps stack (origin!). throw new X(e) wraps (chain via getCause()!).
  • Re-throw checked needs throws on method (still checked!).
  • Don't swallow: empty catch {} hides bugs (log or re-throw ALWAYS!).

4. When? (viva line!)

Low can't decide (library!) → log + re-throw. High knows policy (retry? default? abort!) → final catch.

5. Exam Points

  • Re-throw + wrap program — 5 marks, frequent.
  • Swallow-trap + throws need — 3 marks, frequent.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules