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 viagetCause()!).- Re-throw checked needs
throwson 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 +
throwsneed — 3 marks, frequent.