Exceptions and error handling
41 questions in 14 subtopics.
Throwable hierarchy
Describe the Throwable hierarchy: Error, Exception,RuntimeException. Which are checked, and why should code rarely catch Throwable or Error?A scheduled task in an ExecutorService stops running without any log line. The code catches Exception inside the task. What can be going on?Checked vs unchecked exceptions
What is the difference between checked and unchecked exceptions? Give an example of each from the JDK and explain when to use which.Spring translates checked SQLExceptions into an uncheckedDataAccessException hierarchy, and many modern libraries use only unchecked exceptions. Is that the right default for your services? Argue both sides.Checked exceptions are a Java-specific feature that later JVM languages such as Kotlin and Scala dropped. Explain why Java has them, why the experiment is widely judged mixed, and what policy you would set for a large Java organization today.Try-with-resources and AutoCloseable
Rewrite this with try-with-resources and explain what it guarantees:BufferedReader r = new BufferedReader(new FileReader(path));
try {
return r.readLine();
} finally {
r.close();
}
AutoCloseable correctly, including idempotent close, thread safety, and a safety net for callers who forget to close?Connection pool exhaustion incidents recur across services. Investigation shows JDBC connections and HTTP responses not closed on error paths. How do you fix this at scale?Suppressed exceptions
What does this print, and how would you see the lost exception before Java 7?class R implements AutoCloseable {
public void close() {
throw new IllegalStateException("close");
}
}
try (R r = new R()) {
throw new RuntimeException("body");
} catch (Exception e) {
System.out.println(e.getMessage() + " " + e.getSuppressed().length);
}
e.getMessage(), or a custom log formatter drops causes and suppressed exceptions. How do you fix this across services?Custom exceptions and chaining
Write a custom unchecked exceptionOrderNotFoundException that carries the order ID and supports chaining. What constructors should it have?A service logs throw new ServiceException("Failed to load customer") inside a catch block, and support cannot find why loading failed. What is wrong and how do you review for it?Design an exception hierarchy for a shared platform library used by many services, including how it maps to HTTP errors and error codes.Finally semantics and return
What does this method return, and what happens to the exception?static int f() {
try {
throw new RuntimeException("x");
} finally {
return 42;
}
}
static int g() {
int x = 1;
try {
return x;
} finally {
x = 2;
System.out.print("finally ");
}
}
System.out.println(g());
Exception handling design
A thread pool task catchesInterruptedException with an empty catch block. Shutdown of the service now hangs. Explain why and fix it.Review this code and list the problems:try {
process(order);
} catch (Exception e) {
e.printStackTrace();
}
Errors such as StackOverflowError and OutOfMemoryError
What causesStackOverflowError, and how can you fix deep recursion that triggers it in production?A service throws OutOfMemoryError with different messages on different days: "Java heap space", "Metaspace", "unable to create native thread", and "Direct buffer memory". What does each indicate and how do you investigate?What should the fleet-wide policy be when a JVM throws OutOfMemoryError in a containerised service? Consider heap dumps, restarts and alerting.Over several years your fleet has had recurring incidents where services kept running in a broken state after OutOfMemoryError or StackOverflowError was caught by broad catch blocks. What organization-wide decision do you make and how do you enforce it?Exceptions and performance
What makes exceptions expensive in Java, and how can you reduce the cost when exceptions are thrown frequently, for example in a parser?Production logs showNullPointerException with no stack trace and no message after the service has been running for a while, while early occurrences had full traces. Explain.Exception design decisions in core libraries affect performance, debuggability and API stability for many years. What principles would you set for exception use in your organization's shared libraries, and how do you check them over time?NullPointerException and null handling
A service logs:java.lang.NullPointerException: Cannot invoke "String.length()" because the return value of "com.acme.Customer.getEmail()" is null. Which Java feature produced this message, and how would you fix and prevent the bug?Your codebase mixes null returns, Optional, empty collections and exceptions for missing values, causing frequent NPEs. What conventions and tooling would you introduce for a large service?Tony Hoare called null references his billion-dollar mistake. Kotlin built nullness into its type system, and Java is adding null-restricted types through Valhalla work (check your version). How should a company with millions of lines of Java plan for nullness over the next decade?Standard runtime exceptions
Name common standard unchecked exceptions in the JDK (IllegalArgumentException, IllegalStateException, UnsupportedOperationException, IndexOutOfBoundsException, ConcurrentModificationException, ArithmeticException) and when your own code should throw each one.A single-threaded loop throws ConcurrentModificationException: for (Order o : orders) if (o.isCancelled()) orders.remove(o); Explain why and give three correct alternatives.In a shared library used by 80 services, how should you choose between standard JDK exceptions and custom exception types, and how do you keep those decisions stable across versions?Throw and throws
What is the difference between throw and throws? Can an overriding method declare more checked exceptions than the method it overrides? Give an example.Lambdas passed toStream.map cannot throw checked exceptions such as IOException. Show two ways to handle a method Path to String that throws IOException inside a stream, and say which you prefer.Assertions with assert
How does the Java assert statement work, when is it enabled, and why should it never be used to validate method arguments in public APIs?A developer adds assert statements to check invariants in a payment calculation and tests pass. In production the invariants are violated without any error. Explain what happened and how you would handle invariants that matter in production.Stack traces
Read this stack trace and say where the bug is and how you would find the root cause:com.acme.ServiceException: Failed to load order 42 at OrderService.load(OrderService.java:57) ... Caused by: org.hibernate.exception.SQLGrammarException ... Caused by: org.postgresql.util.PSQLException: ERROR: column o.status_code does not existWhat does filling in a stack trace cost, how does StackWalker differ from Thread.getStackTrace, and when would you create an exception with writableStackTrace=false?Logs across your services are flooded with 300-line stack traces from framework layers, cost is high, and on-call engineers still cannot find root causes quickly. What would you change?No question matches these choices.