Skip to lesson

Error handling interview review

A handful of error handling questions come up in almost every Java interview. Each has a short rule and a design reason behind it, and the strongest answers give both, with a small example ready.

Checked versus unchecked

A checked exception extends Exception (not RuntimeException); the compiler forces callers to catch it or declare it with throws. An unchecked exception extends RuntimeException, and the compiler leaves callers free. Errors such as OutOfMemoryError are also unchecked, and normal code should not catch them.

Example 1 · The two kinds side by side

TwoKindsDemo.javaJava
class FeeDueException extends Exception {    FeeDueException(String roll) {        super("Fee is due for roll " + roll);    }}
public class TwoKindsDemo {    static void issueHallTicket(String roll, boolean feePaid) throws FeeDueException {        if (roll == null || roll.isBlank()) {            throw new IllegalArgumentException("roll is required");   // unchecked: a bug        }        if (!feePaid) {            throw new FeeDueException(roll);                          // checked: expected        }        System.out.println("Hall ticket issued for " + roll);    }
    public static void main(String[] args) {        try {            issueHallTicket("101", true);            issueHallTicket("102", false);        } catch (FeeDueException e) {          // the compiler insists on this catch (or throws)            System.out.println(e.getMessage() + ". Pay at the accounts office.");        }        try {            issueHallTicket(" ", true);        } catch (FeeDueException | IllegalArgumentException e) {            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());        }    }}
Output
Hall ticket issued for 101
Fee is due for roll 102. Pay at the accounts office.
IllegalArgumentException: roll is required

What this code does

  • FeeDueException is checked, so issueHallTicket declares it and every caller must handle it; the fee office is a sensible next step for the user.
  • A blank roll number is a bug in the caller, so it is the unchecked IllegalArgumentException, which needs no throws clause.

The interview answer has two parts: the rule, and the design choice. Checked for expected problems a caller can recover from (seat sold out, file chosen by the user is missing); unchecked for bugs and broken rules (negative amount, null name). Add that checked exceptions do not pass through lambdas, which is one reason modern code leans to unchecked.

finally versus try-with-resources

A finally block runs after the try (and any catch), whether the code finished normally, returned or threw. try-with-resources (try (Reader r = ...)) closes every AutoCloseable declared in its brackets automatically, in reverse order, before any catch or finally of the same statement runs.

Example 2 · Close order with try-with-resources, catch and finally

CloseOrderDemo.javaJava
class Resource implements AutoCloseable {    private final String name;
    Resource(String name) {        this.name = name;        System.out.println("open " + name);    }
    @Override    public void close() {        System.out.println("close " + name);    }}
public class CloseOrderDemo {    public static void main(String[] args) {        try (Resource marks = new Resource("marks.csv");             Resource report = new Resource("report.txt")) {            System.out.println("working");            throw new IllegalStateException("bad row 7");        } catch (IllegalStateException e) {            System.out.println("catch: " + e.getMessage());        } finally {            System.out.println("finally");        }    }}
Output
open marks.csv
open report.txt
working
close report.txt
close marks.csv
catch: bad row 7
finally

What this code does

  • Resources open in the order they are declared and close in reverse order: report.txt first, then marks.csv.
  • Both are closed before the catch block runs, and finally runs last. Interviewers like this exact order.

finally is skipped only by System.exit or a JVM crash.

For closing things, try-with-resources is shorter and safer: no null checks, no nested try, and no lost exceptions. finally is still right for clean-up that is not a resource, such as unlocking a lock or resetting a flag.

Suppressed exceptions

A suppressed exception is a second exception that happened while closing a resource after the main work had already failed. Try-with-resources keeps the main exception and attaches the one from close() to it with addSuppressed.

Example 3 · Suppressed: the main exception survives

SuppressedDemo.javaJava
class FlakyResource implements AutoCloseable {    @Override    public void close() {        throw new IllegalStateException("close failed");    }}
public class SuppressedDemo {    static void oldStyle() {        FlakyResource r = new FlakyResource();        try {            throw new IllegalArgumentException("import failed at row 7");        } finally {            r.close();                 // its exception replaces the main one        }    }
    static void newStyle() {        try (FlakyResource r = new FlakyResource()) {            throw new IllegalArgumentException("import failed at row 7");        }    }
    public static void main(String[] args) {        try {            oldStyle();        } catch (RuntimeException e) {            System.out.println("finally style: " + e.getMessage()                    + " (suppressed: " + e.getSuppressed().length + ")");        }        try {            newStyle();        } catch (RuntimeException e) {            System.out.println("try-with-resources: " + e.getMessage());            for (Throwable s : e.getSuppressed()) {                System.out.println("  suppressed: " + s.getMessage());            }        }    }}
Output
finally style: close failed (suppressed: 0)
try-with-resources: import failed at row 7
  suppressed: close failed

What this code does

  • In oldStyle, close() throws inside finally, and that exception replaces the real one: the caller sees only close failed and never learns that row 7 was the problem.
  • In newStyle, try-with-resources keeps the main exception and attaches the close failure to it, so getSuppressed() returns both pieces of the story.

Read the attached exceptions back with getSuppressed(); a stack trace shows them under Suppressed:.

Old finally { r.close(); } code had a nasty bug here: if close() threw, its exception replaced the main one, and the real reason for the failure was lost.

throw versus throws, final versus finally

throw is a statement that throws one exception object now: throw new SeatLimitException(75);. throws is part of a method header that lists the checked exceptions the method may let out: void reserve(int seats) throws SeatLimitException.

Example 4 · throw, throws, final and finally in one program

KeywordsDemo.javaJava
class SeatLimitException extends Exception {    SeatLimitException(int seats) {        super("Cannot reserve " + seats + " seats, limit is " + KeywordsDemo.MAX_SEATS);    }}
public class KeywordsDemo {    static final int MAX_SEATS = 60;
    static void reserve(int seats) throws SeatLimitException {   // throws: declares        if (seats > MAX_SEATS) {            throw new SeatLimitException(seats);            // throw: throws it now        }        System.out.println("Reserved " + seats + " seats");    }
    public static void main(String[] args) {        for (int seats : new int[]{40, 75}) {            try {                reserve(seats);            } catch (SeatLimitException e) {                System.out.println(e.getMessage());            } finally {                                     // finally: always runs                System.out.println("finally runs for " + seats);            }        }    }}
Output
Reserved 40 seats
finally runs for 40
Cannot reserve 75 seats, limit is 60
finally runs for 75

What this code does

  • throws SeatLimitException in the header only warns callers; the throw statement inside the if is what actually throws.
  • final on MAX_SEATS means it can never change, and finally runs on both paths: after the normal reservation and after the exception was caught.

final makes a variable unchangeable after it is set, a method impossible to override, or a class impossible to extend. finally is the clean-up block after try. They only sound alike. A third look-alike, Object.finalize(), was a clean-up hook called before garbage collection; it is deprecated since Java 9 and marked for removal since Java 18, so never rely on it.

Designing errors for a small app

Interviewers often ask how you would handle errors in a small app.

Example 5 · A small online shop with a complete error design

ShopAppDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.logging.Level;import java.util.logging.Logger;
class ShopException extends RuntimeException {    ShopException(String message) { super(message); }    ShopException(String message, Throwable cause) { super(message, cause); }}
class ItemNotFoundException extends ShopException {    ItemNotFoundException(String item) {        super("Sorry, '" + item + "' is not in our catalogue.");    }}
class StorageException extends ShopException {    StorageException(String message, Throwable cause) { super(message, cause); }}
record Order(String item, int quantity) {    Order {        Objects.requireNonNull(item, "item must not be null");        if (quantity < 1 || quantity > 10) {            throw new IllegalArgumentException("quantity must be 1 to 10, got " + quantity);        }    }}
class CatalogueStorage {                                             // translate at the boundary    private final Path file;
    CatalogueStorage(Path file) { this.file = file; }
    Map<String, Integer> load() {        try {            Map<String, Integer> catalogue = new HashMap<>();            for (String line : Files.readAllLines(file)) {                String[] parts = line.split(",");                catalogue.put(parts[0], Integer.parseInt(parts[1]));            }            return catalogue;        } catch (IOException e) {            throw new StorageException("Catalogue is not available right now.", e);        }    }}
class OrderService {    private final CatalogueStorage storage;
    OrderService(CatalogueStorage storage) { this.storage = storage; }
    int bill(Order order) {        Integer price = storage.load().get(order.item());        if (price == null) {            throw new ItemNotFoundException(order.item());        }        return price * order.quantity();    }}
public class ShopAppDemo {    static {   // only for this page: short log lines on System.out (no date, no stack trace)        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n");    }
    private static final Logger LOG = Logger.getLogger(ShopAppDemo.class.getName());
    static void handle(OrderService service, String item, int quantity) {   // top-level handler        try {            int amount = service.bill(new Order(item, quantity));            System.out.println(quantity + " x " + item + " = Rs " + amount);        } catch (StorageException e) {            LOG.log(Level.SEVERE, "Catalogue storage failed", e);            System.out.println(e.getMessage());        } catch (ShopException e) {            System.out.println(e.getMessage());        } catch (RuntimeException e) {            LOG.log(Level.SEVERE, "Unexpected error for order " + item, e);            System.out.println("Something went wrong. Please ask at the counter.");        }    }
    public static void main(String[] args) throws IOException {        Path folder = Files.createTempDirectory("shop");        Path catalogue = folder.resolve("catalogue.csv");        Files.write(catalogue, List.of("Monitor,7500", "Keyboard,900"));        OrderService service = new OrderService(new CatalogueStorage(catalogue));
        handle(service, "Keyboard", 2);        handle(service, "Webcam", 1);        handle(service, "Monitor", 0);        Files.delete(catalogue);        handle(service, "Monitor", 2);        Files.delete(folder);    }}
Output
2 x Keyboard = Rs 1800
Sorry, 'Webcam' is not in our catalogue.
SEVERE: Unexpected error for order Monitor
Something went wrong. Please ask at the counter.
SEVERE: Catalogue storage failed
Catalogue is not available right now.

What this code does

  • Each layer does one job: Order rejects bad values, CatalogueStorage turns IOException into StorageException with the cause, OrderService throws app exceptions with user-ready messages, and only handle catches.
  • A missing item is the user's choice, so it gets a message and no log. Quantity 0 should have been caught by the input screen, so it is treated as a bug and logged. The missing catalogue file is logged as SEVERE with its cause, and the user sees a calm sentence.

A complete answer joins up the whole module:

  • Validate early: guard clauses and record compact constructors with IllegalArgumentException.
  • One base exception for the app; children only where a caller catches them separately; messages with the bad value.
  • Translate at layer boundaries (IOException → StorageException), always keeping the cause.
  • One top-level handler: user-safe messages, SEVERE logs with stack traces, exit codes; retries only for temporary errors.

Next step

Check your understanding

12 quick questions