Scrivio Interview library

Exceptions and error handling

41 questions in 14 subtopics.

Throwable hierarchy

ConceptFoundations5 min read
Describe the Throwable hierarchy: Error, Exception, RuntimeException. Which are checked, and why should code rarely catch Throwable or Error?
DebuggingIntermediate6 min read
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

ConceptFoundations5 min read
What is the difference between checked and unchecked exceptions? Give an example of each from the JDK and explain when to use which.
LeadershipIntermediate6 min read
Spring translates checked SQLExceptions into an unchecked DataAccessException hierarchy, and many modern libraries use only unchecked exceptions. Is that the right default for your services? Argue both sides.
ConceptPrincipal7 min read
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

CodingFoundations6 min read
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();
}
DesignIntermediate6 min read
You design a class that holds a native resource or a connection. How do you implement AutoCloseable correctly, including idempotent close, thread safety, and a safety net for callers who forget to close?
ScenarioAdvanced6 min read
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

CodingIntermediate6 min read
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);
}
ScenarioAdvanced7 min read
Incident reviews show that root causes are often missing from logs because logs only print e.getMessage(), or a custom log formatter drops causes and suppressed exceptions. How do you fix this across services?

Custom exceptions and chaining

CodingFoundations6 min read
Write a custom unchecked exception OrderNotFoundException that carries the order ID and supports chaining. What constructors should it have?
DebuggingIntermediate6 min read
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?
DesignAdvanced7 min read
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

CodingFoundations5 min read
What does this method return, and what happens to the exception?
static int f() {
try {
throw new RuntimeException("x");
} finally {
return 42;
}
}
CodingFoundations5 min read
What does this print?
static int g() {
int x = 1;
try {
return x;
} finally {
x = 2;
System.out.print("finally ");
}
}
System.out.println(g());
InternalsIntermediate7 min read
How does javac compile finally blocks, and why can large finally blocks matter for method size and JIT compilation?

Exception handling design

DebuggingFoundations6 min read
A thread pool task catches InterruptedException with an empty catch block. Shutdown of the service now hangs. Explain why and fix it.
DebuggingFoundations6 min read
Review this code and list the problems:
try {
process(order);
} catch (Exception e) {
e.printStackTrace();
}
ScenarioIntermediate7 min read
Your REST services return stack traces in error responses in some cases and generic 500s with no detail in others. How do you design consistent error handling for a Spring Boot service?
LeadershipAdvanced6 min read
Teams across your organization handle errors inconsistently: some use exceptions for control flow, some return null, some return result objects. What standard do you set, and how do you roll it out?
LeadershipPrincipal7 min read
Across a company with hundreds of Java services, how would you define what an error is, how it is represented in code, logs, metrics and APIs, and who owns that standard over the years?

Errors such as StackOverflowError and OutOfMemoryError

ConceptFoundations7 min read
What causes StackOverflowError, and how can you fix deep recursion that triggers it in production?
DebuggingIntermediate7 min read
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?
DesignAdvanced7 min read
What should the fleet-wide policy be when a JVM throws OutOfMemoryError in a containerised service? Consider heap dumps, restarts and alerting.
ScenarioPrincipal7 min read
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

InternalsIntermediate7 min read
What makes exceptions expensive in Java, and how can you reduce the cost when exceptions are thrown frequently, for example in a parser?
DebuggingIntermediate6 min read
Production logs show NullPointerException with no stack trace and no message after the service has been running for a while, while early occurrences had full traces. Explain.
LeadershipPrincipal6 min read
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

DebuggingFoundations7 min read
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?
DesignIntermediate7 min read
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?
LeadershipPrincipal6 min read
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

ConceptFoundations7 min read
Name common standard unchecked exceptions in the JDK (IllegalArgumentException, IllegalStateException, UnsupportedOperationException, IndexOutOfBoundsException, ConcurrentModificationException, ArithmeticException) and when your own code should throw each one.
DebuggingIntermediate7 min read
A single-threaded loop throws ConcurrentModificationException: for (Order o : orders) if (o.isCancelled()) orders.remove(o); Explain why and give three correct alternatives.
DesignAdvanced7 min read
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

ConceptFoundations5 min read
What is the difference between throw and throws? Can an overriding method declare more checked exceptions than the method it overrides? Give an example.
CodingIntermediate6 min read
Lambdas passed to Stream.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

ConceptFoundations6 min read
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?
ScenarioIntermediate6 min read
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

DebuggingFoundations6 min read
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 exist
InternalsIntermediate6 min read
What does filling in a stack trace cost, how does StackWalker differ from Thread.getStackTrace, and when would you create an exception with writableStackTrace=false?
ScenarioAdvanced7 min read
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?