Interview
Exceptions — Interview Questions (77+)
See `pkg1core/core18ExceptionsDemo.java`.
Detailed Questions
1. Exception hierarchy in Java?
- Short:
Throwable→Error(don't catch) andException→ checked vsRuntimeException(unchecked). - Detailed: Checked exceptions extend
Exception(notRuntimeException) and must be declared or caught. Unchecked are programming bugs or unrecoverable usage (NPE,IllegalArgumentException).Errorsignals serious JVM problems (OutOfMemoryError,StackOverflowError). - Example:
IOExceptionchecked;NullPointerExceptionunchecked.
2. When to use checked vs unchecked?
- Short: Checked for recoverable, expected failures; unchecked for bugs and programming errors.
- Detailed: Modern style favors unchecked for most application code (Spring, Hibernate use unchecked wrappers). Checked forces every caller to handle — can clutter APIs. Use checked when the caller can meaningfully recover (retry I/O).
- Example: File not found → checked
IOExceptionor wrap inUncheckedIOException.
3. try-with-resources — how does it work?
- Short: Auto-closes
AutoCloseableresources; suppresses close exceptions properly. - Detailed: Compiler desugars to try/finally with
close()called. If both try and close throw, primary exception is preserved; close exception is suppressed. Resources declared in try header must be effectively final. - Example:
try (var in = Files.newInputStream(path)) { ... }
4. Multi-catch and rethrow rules?
- Short:
catch (A | B e)if A and B are unrelated; can't combine if one subclasses the other. - Detailed: Catch parameter is implicitly
final. Rethrowing narrows the declared type if the catch block only throws a subtype. Annotate with@Throwsfor documentation. - Example:
catch (SQLException | IOException e).
5. Exception chaining — why?
- Short: Preserve root cause when wrapping at layer boundaries.
- Detailed:
new ServiceException("save failed", sqlEx)keeps stack trace of original. Withoutcause, debugging production issues is painful. Always passcauseto wrapper constructor. - Example:
throw new DataAccessException("user " + id, e);
6. finally vs try-with-resources?
- Short:
finallyalways runs (unlessSystem.exit); try-with-resources is the idiomatic close pattern. - Detailed:
returnin try still runsfinallybefore actually returning (can clobber return value if finally also returns). Prefer try-with-resources over manual finally-close. - Example: Returning from try while finally modifies state — gotcha in interviews.
7. Custom exception design?
- Short: Extend
Exceptionfor checked,RuntimeExceptionfor unchecked; meaningful messages; optional error codes. - Detailed: Provide constructors
(String),(String, Throwable),(Throwable). Don't over-hierarchy. Domain exceptions (InsufficientFundsException) aid handling at boundaries. - Example: See
core18ExceptionsDemo.InsufficientFundsException.
8. Should you catch `Exception` or `Throwable`?
- Short: Avoid broad catch in application code; catch specific types.
- Detailed:
catch (Exception e)swallows programming bugs.catch (Throwable)includesError— almost never correct. Top-level handlers (HTTP filter) may log and map to 500. - Example: Framework
@ControllerAdvicemapsValidationException→ 400, unknown → 500.
9. Stack trace cost and logging?
- Short: Creating exceptions is cheap until you read stack trace; logging fills stack at throw/catch site.
- Detailed:
new Exception()without throw is sometimes used for stack capture (expensive). Use logging frameworks; don'tprintStackTrace()in production. Include correlation IDs. - Example:
log.error("order {} failed", id, ex);
10. Suppressed exceptions?
- Short: Secondary exceptions during close/add suppressed to primary.
- Detailed:
Throwable.getSuppressed()returns them. Important when debugging try-with-resources with multiple failures. - Example: Read fails, then close also fails — both visible.
11. Assertions vs exceptions?
- Short:
assertfor internal invariants (disabled by default); exceptions for contract violations callers should handle. - Detailed: Enable with
-ea. Never use assert for user input validation — it can be off in production. - Example:
assert index >= 0in private method after internal logic.
12. Best practices for exception messages?
- Short: Actionable, include context (ids, operation), no secrets.
- Detailed: "Failed to save order 12345 for user 99" beats "Error". Don't log passwords or tokens. Internationalize user-facing messages separately from log messages.
- Example:
throw new OrderNotFoundException(orderId);
Rapid-Fire (Q → A)
- Root of exceptions? → Throwable.
- Don't catch? → Error (generally).
- Checked parent? → Exception (not RuntimeException).
- Unchecked parent? → RuntimeException.
- Must declare checked? → throws or catch.
- NPE type? → Unchecked.
- IllegalArgumentException when? → Bad argument to method.
- IllegalStateException when? → Object state wrong for call.
- IOException? → Checked I/O failure.
- try-with-resources interface? → AutoCloseable.
- Closeable vs AutoCloseable? → Closeable extends AutoCloseable; close throws IOException.
- Multi-catch restriction? → No subclass + supertype together.
- Catch param final? → Implicitly final.
- throw vs throws? → throw statement vs method signature.
- throw null? → NPE at throw site.
- finally without catch? → Yes, try-finally.
- finally always runs? → Except System.exit / JVM crash.
- return in try + finally? → finally runs before return completes.
- try-with-resources compile? → Desugared to try-finally-close.
- Suppressed exceptions API? → getSuppressed(), addSuppressed().
- initCause? → Set cause after construction (once).
- getCause? → Underlying throwable.
- fillInStackTrace? → Capture stack; expensive.
- printStackTrace production? → Avoid; use logger.
- Rethrow same exception? → Stack trace preserved.
- Wrap and throw new? → Pass cause constructor.
- Exception as control flow? → Anti-pattern (e.g. parse int via exception).
- Validation: exception vs return code? → Exception or Result type for domain.
- Optional vs exception for missing? → Optional for expected absence; exception for exceptional.
- Business vs technical exception? → Business may map to 4xx; technical to 5xx.
- Retry on which exceptions? → Transient (timeout), not validation.
- Idempotent retry safe? → Design operations accordingly.
- Circuit breaker relation? → Stop calling failing dependency.
- Global exception handler Spring? → @ControllerAdvice.
- Servlet filter exception? → Map to error response.
- SQLException checked? → Yes (often wrapped by JDBC templates).
- DataAccessException? → Spring unchecked wrapper.
- PersistenceException? → JPA unchecked wrapper.
- CompletionException? → Wraps async stage failures.
- ExecutionException? → Future.get() wrapper.
- UncheckedIOException? → Wrap checked IO.
- Sneaky throws (Lombok)? → Controversial; hides checked.
- try-catch-performance? → No cost when no throw; throw is expensive.
- Table exception in DB? → Use SQL state codes.
- OOM catchable? → Technically yes; rarely recoverable.
- StackOverflowError? → Usually infinite recursion.
- ExceptionInInitializerError? → Static init failed.
- Unhandled exception thread? → Default handler prints and may exit.
- setDefaultUncaughtExceptionHandler? → Custom thread crash handling.
- try-with multiple resources? → Semicolon-separated; closed reverse order.
- Resource must be? → Effectively final.
- Custom close exception? → Added as suppressed.
- try-with on String? → No; String not AutoCloseable.
- Cleaner (Java 9+)? → Alternative to finalize for native cleanup.
- PhantomReference use? → Post-mortem cleanup.
- finalize status? → Deprecated; don't use.
- try-catch in loop? → OK; avoid throw as normal path.
- Exception hierarchy design? → Shallow tree preferred.
- Error codes + exceptions? → Complement, not replace.
- Log and rethrow? → Yes at boundary; don't swallow.
- Swallow exception smell? → Empty catch block.
- catch log throw? → Preserve stack with cause.
- fail-fast collections? → CME on concurrent mod.
- CME is unchecked? → Yes, RuntimeException.
- Specifying behavior in javadoc? → @throws tags.
Source named in this chapter
- core18ExceptionsDemopkg1core/core18ExceptionsDemo.java