About Us Contact Us Write for Us Advertise
Home > Java > Java Exception Handling Interview Questions (Traps & Best Practices) — Freshers to Senior
Java

Java Exception Handling Interview Questions (Traps & Best Practices) — Freshers to Senior

A senior-level Java exception-handling interview guide: the Throwable hierarchy, checked vs unchecked design decisions, try-with-resources and suppressed exceptions, finally traps, precise rethrow, exception chaining, checked exceptions with lambdas/streams, NPE avoidance, and best practices.

Shiv Pandey
Shiv Pandey
Oct 10, 2026 | 187 views
Java Exception Handling Interview Questions (Traps & Best Practices) — Freshers to Senior

Exception handling looks like the easiest interview topic — until you're asked "what does finally print when both try and finally return?" or "why do checked exceptions break lambdas?" This is a senior-level exception-handling interview guide: the full Throwable hierarchy and the checked/unchecked design decision, try-with-resources and suppressed exceptions, the finally-return and swallowed-exception traps, precise rethrow, exception chaining, why checked exceptions and streams don't mix, and the performance cost interviewers rarely expect you to know.

What separates seniors here: not knowing try/catch syntax, but having a policy — which exceptions to make checked vs unchecked, where to catch vs propagate, how to wrap without losing the cause, and why swallowing an exception is the worst bug you can ship. Bring opinions, backed by reasons.

The hierarchy & the big design question

Q1. Draw the exception hierarchy.

Throwable
├── Error            // JVM-level, don't catch (OutOfMemoryError, StackOverflowError)
└── Exception
    ├── RuntimeException  // UNCHECKED (NPE, IllegalArgument, IndexOutOfBounds)
    └── (others)          // CHECKED (IOException, SQLException)

Q2. Checked vs unchecked — when should an exception be each?

Checked (compiler-enforced throws/catch) is for recoverable, expected conditions the caller should handle — a missing file, a network blip. Unchecked (RuntimeException) is for programming errors the caller usually can't recover from — a null argument, an illegal state, an index out of range. Rule: if the caller can realistically do something about it, checked; if it's a bug, unchecked. Modern APIs and Spring lean heavily unchecked (fewer boilerplate throws clauses).

Q3. Should you ever catch Error or Throwable?

No — Error signals the JVM is in an unrecoverable state (heap exhausted, stack blown). Catching Throwable also traps Error and hides real bugs. Catch the narrowest exception you can actually handle; let the rest propagate.

The traps interviewers love

Q4. Predict the output — return in try vs finally.

int f() {
    try { return 1; }
    finally { return 2; }  // overrides the try's return!
}
// f() returns 2 — a return in finally silently swallows the try's return AND any exception.

Never return (or throw) from finally — it discards whatever the try/catch was doing, including a pending exception. This is a classic "spot the bug" question.

Q5. Predict the output — exception thrown in both try and finally.

try { throw new RuntimeException("A"); }
finally { throw new RuntimeException("B"); }
// Only "B" propagates. "A" is LOST — the finally exception replaces it.

An exception from finally masks the original. Try-with-resources fixes exactly this (Q6) by suppressing rather than discarding.

try-with-resources & suppressed exceptions

Q6. How does try-with-resources work, and what are suppressed exceptions?

try (var in = new FileInputStream(f);
     var out = new FileOutputStream(g)) {   // both AutoCloseable
    // ... use in, out
}   // close() called automatically, in REVERSE order (out then in)

Any resource implementing AutoCloseable is closed automatically, even on exception, in reverse declaration order. If the body throws and close() throws, the body's exception is the primary one and the close exception is suppressed — attached and retrievable via getSuppressed(), so nothing is lost. This is strictly better than a manual finally { close(); }, which would mask the original (Q5).

Precise handling & chaining

Q7. Multi-catch and precise rethrow (Java 7).

try { risky(); }
catch (IOException | SQLException e) {  // one block, two types
    log.error("failed", e);
    throw e;  // compiler knows the precise type, not just Exception
}

Multi-catch removes duplicate blocks; the caught variable is effectively final. Note you can't multi-catch types in a subclass relationship (redundant).

Q8. Exception chaining — why wrap with a cause?

catch (SQLException e) {
    throw new DataAccessException("save failed", e); // pass e as cause
}
// "Caused by: SQLException..." preserved in the stack trace.

Translate low-level exceptions to your layer's abstraction (so callers don't depend on SQLException), but always pass the original as the cause — dropping it destroys the root-cause trail and makes production debugging miserable. This is a defining senior habit.

Checked exceptions meet functional Java

Q9. Why do checked exceptions clash with lambdas and streams?

// Won't compile — Function.apply() declares no checked exception
paths.stream().map(p -> Files.readAllBytes(p)) // IOException = checked
// Fix: wrap into an unchecked exception inside the lambda
paths.stream().map(p -> {
    try { return Files.readAllBytes(p); }
    catch (IOException e) { throw new UncheckedIOException(e); }
})

The functional interfaces (Function, Supplier) don't declare checked exceptions, so a lambda can't throw one. You must catch-and-wrap (often into UncheckedIOException/RuntimeException) or use a helper. This friction is a big reason modern Java favours unchecked exceptions.

NullPointerException & best practices

Q10. How do you avoid NPEs? What did Java 14 add?

Use Optional for "maybe absent" return values (never for fields/params), Objects.requireNonNull to fail fast at boundaries, and prefer "literal".equals(var) ordering or Objects.equals. Java 14 Helpful NullPointerExceptions now name the exact variable that was null ("Cannot invoke ... because user.address is null"), turning a guessing game into a one-line fix. See NullPointerException explained.

Q11. What's the performance cost of exceptions?

Creating an exception is expensive because the constructor calls fillInStackTrace(), walking the whole call stack. So never use exceptions for control flow (e.g. throwing to break a loop) in hot paths. If you truly need a lightweight signal, override fillInStackTrace() to skip stack capture — but that's a rare optimisation, not a default.

Q12. Exception-handling best practices — the checklist.

  • Never swallow — an empty catch {} hides bugs; at minimum log with the exception object.
  • Catch the narrowest type you can handle; don't catch Exception broadly.
  • Wrap with cause, never catch(e){ throw new X(e.getMessage()); } — that drops the trace.
  • Use try-with-resources for anything AutoCloseable.
  • Fail fast — validate arguments at the top and throw IllegalArgumentException early.
  • Don't log and rethrow the same exception (double-logging noise) — do one.

Rapid-fire

  • throw vs throws? throw raises an exception instance; throws declares that a method may propagate one.
  • Can finally not run? Only if the JVM exits (System.exit), the thread is killed, or the machine dies.
  • Can a constructor throw? Yes — and it's the right way to reject invalid construction.
  • Custom exception: extend which? RuntimeException for unchecked, Exception for checked; add a (String, Throwable) constructor to support chaining.
  • Checked exception in an overriding method? Can only throw the same or narrower checked exceptions than the parent (see OOP rules).

Go deeper by topic

The habit that changed how I handle exceptions: I stopped thinking "how do I make this compile?" and started thinking "what does the person debugging this at 2am need?" That one shift answers almost every question on this page. They need the root cause, so I always chain with the original. They need to know where, so I never swallow and never return from finally. They need resources closed even on failure, so try-with-resources is automatic. They need the exception type to tell them whether it's their bug or mine, so I pick checked vs unchecked deliberately. Design your error handling for the future debugger — often yourself — and you'll answer these questions with the calm authority of someone who's actually maintained a system, which is exactly the signal interviewers are hunting for. You've got this.

Related

← Multithreading interview questions · Spring Boot interview questions →

Related Articles

Java Multithreading Interview Questions (JMM, Locks & Traps) — Freshers to Senior
Java

Java Multithreading Interview Questions (JMM, Locks & Traps) — Freshers to Senior

Java Collections Interview Questions (Internals & Traps) — Freshers to Senior
Java

Java Collections Interview Questions (Internals & Traps) — Freshers to Senior

OOP Interview Questions in Java (With Code & Traps) — Freshers to Senior
Java

OOP Interview Questions in Java (With Code & Traps) — Freshers to Senior

DSA Interview Questions in Java (Patterns, Not Problems) — Freshers to Senior
Java

DSA Interview Questions in Java (Patterns, Not Problems) — Freshers to Senior