GamifiedGamified challengesPracticeRaceLeaderboardPricing

Learn data structures by watching them move, then doing it yourself. Press M anytime to toggle sound.

A product of Amypo Technologies, Coimbatore.

Learn

  • All topics
  • Learning path
  • How it works
  • About dotprep

Practice

  • Practice arena
  • Daily challenge
  • Gamified challenges
  • Race mode
  • Leaderboard

Interview prep

  • Java interview
  • Coding questions
  • Company questions
  • System design
  • Jobs & careers

You

  • Dashboard
  • Settings
  • Pricing
  • Create account

© 2026 dotprep

Content last updated 20 November 2026

GamifiedGamified challengesPracticeRaceLeaderboardPricing
Java interviewException handling

Exception handling

Checked vs unchecked, try-with-resources, finally's surprises, and how to design your own exceptions.

beginner 12 min read 7 interview questions

On this page

1/6
  1. 01The exception hierarchy
  2. 02try, catch, finally and try-with-resources
  3. 03finally edge cases
  4. 04Custom exceptions and good practice
  5. 05Interview questions
  6. 06Quick check
Back to top

The exception hierarchy

  • Throwable is the root.
  • Error: serious JVM problems you normally don't catch (OutOfMemoryError, StackOverflowError).
  • Exception: problems a program can handle.
  • RuntimeException and its subclasses are unchecked (NullPointerException, IllegalArgumentException, IndexOutOfBoundsException).
  • Every other Exception is checked (IOException, SQLException): the compiler forces you to catch it or declare it with throws.

Rule of thumb: checked exceptions for conditions a caller can reasonably recover from (file missing); unchecked for programming errors (null argument, bad index).

try, catch, finally and try-with-resources

java
try {
int n = Integer.parseInt(input);
process(n);
} catch (NumberFormatException e) { // most specific first
log.warn("not a number: {}", input);
} catch (IOException | SQLException e) { // multi-catch (Java 7+)
throw new ServiceException("processing failed", e); // keep the cause
} finally {
metrics.done(); // runs whether or not something was thrown
}

try-with-resources closes anything that implements AutoCloseable, in reverse order, even if an exception is thrown. Exceptions thrown while closing are attached as suppressed to the main one instead of hiding it.

java
try (var in = Files.newBufferedReader(path);
var out = Files.newBufferedWriter(copy)) {
in.transferTo(out);
} // out.close(), then in.close(), automatically

finally edge cases

  • finally runs after return is evaluated but before the method actually returns.
  • A return inside finally overrides the try's return value and swallows any exception: never do it.
  • finally doesn't run if the JVM exits (System.exit) or the thread is killed.
java
static int f() {
int x = 1;
try { return x; } // the value 1 is saved here
finally { x = 2; } // changing x doesn't change the saved value
}
// f() returns 1

Custom exceptions and good practice

java
public class InsufficientFundsException extends Exception {
private final long shortBy;
public InsufficientFundsException(long shortBy) {
super("Short by " + shortBy);
this.shortBy = shortBy;
}
public long shortBy() { return shortBy; }
}
  • Catch the most specific type you can handle; don't catch Exception or Throwable blindly.
  • Never swallow an exception silently. At least log it, or rethrow.
  • When wrapping, pass the original as the cause so the stack trace survives.
  • Don't use exceptions for normal control flow; they're slow and obscure intent.
  • Fail fast: validate arguments early with Objects.requireNonNull or IllegalArgumentException.

See it animated

Recursion

Interview questions

Try answering out loud first, then open the model answer.

Q1Checked vs unchecked exceptions?beginner

Checked exceptions (subclasses of Exception but not RuntimeException) must be caught or declared with throws; the compiler enforces it. Unchecked ones (RuntimeException, Error) don't. Checked: recoverable external conditions; unchecked: programming bugs.

Q2throw vs throws?beginner

throw actually throws an exception object inside a method body. throws in a method signature declares which checked exceptions the method may let escape to its callers.

Q3Does finally always run?intermediate

Almost always: after normal completion, after a caught or uncaught exception, and after return/break. It doesn't run if the JVM halts (System.exit, a crash) or the thread dies abruptly.

Q4What is try-with-resources and what are suppressed exceptions?intermediate

A try statement that declares AutoCloseable resources and closes them automatically in reverse order. If the body throws and close() also throws, the close exception is attached to the main one via addSuppressed (readable with getSuppressed()) instead of replacing it.

Q5Can you catch multiple exceptions in one block?beginner

Yes, with multi-catch: catch (IOException | SQLException e). The types can't be subclasses of each other, and e is implicitly final.

Q6What does this return? try { return 1; } finally { return 2; }intermediate

2. A return in finally replaces the try block's return value (and would also swallow any exception), which is why returning from finally is considered a bug.

Q7Is it a good idea to catch Exception?intermediate

Rarely. It also catches programming errors you'd rather see fail fast, and hides what can actually go wrong. Catch specific types; a broad catch belongs only at a boundary (top of a request handler or thread) where you log and convert to an error response.

Quick check

Question 1

1.Which is a checked exception?

Question 2

2.try-with-resources requires the resource to implement…

Question 3

3.Order of catch blocks should be…

Question 4

4.StackOverflowError is a…

0 of 4 answered

Strings & memoryCollections framework
Log inStart free