Scrivio Interview library
ScenarioPrincipal7 min read · updated 12 November 2026

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?

I would make it an organization-wide rule that a JVM which has thrown OutOfMemoryError, or another VirtualMachineError, must fail fast and be restarted by the orchestrator, using -XX:+ExitOnOutOfMemoryError in the standard service image. Catching Throwable or Error is forbidden except in a few top-level handlers that log and then rethrow or exit. The rule is enforced by static analysis in CI and by the shared service template, and we track restart counts and memory alerts so that automatic restarts never hide a leak.

Why this question is asked

A service that crashes is an incident everyone sees and fixes. A service that keeps running in a broken state is worse: it passes health checks while dropping messages, holding locks or serving stale data, and the incident lasts hours instead of minutes. When this keeps happening over years, it is no longer a bug in one service but a gap in the organization's defaults. Interviewers ask this at the most senior level to see whether we can make a clear technical decision, explain it in terms of risk, and enforce it across hundreds of services without relying on everyone remembering. In this answer, we will see why a JVM is untrustworthy after these errors, make the decision, define the one place catching is allowed, and go through enforcement and monitoring.

1Why the Process Is Untrustworthy After These Errors

Java separates Exception, for conditions a program may handle, from Error, for serious problems a program should not normally try to handle. VirtualMachineError, the parent of OutOfMemoryError and StackOverflowError, means the JVM itself ran out of a resource. These errors can be thrown at almost any instruction: any allocation can fail, any method call can overflow the stack.

So when one is thrown, it interrupts code at a point the code was never written to be interrupted. A thread updating two related fields may have changed one. A library may have taken a lock and never reached its finally block, or reached it and failed again inside it. A background thread, such as a connection pool's housekeeper, a Kafka consumer's heartbeat or a scheduler, may have died, and nothing restarts it. When a broad catch block swallows the error and the request loop continues, the process looks healthy while parts of it are dead.

Java
// The pattern behind the incidents
while (running) {
try {
handle(queue.take());
} catch (Throwable t) { // also catches OutOfMemoryError and StackOverflowError
log.error("Handler failed", t); // logging may itself fail with another OOM
} // the loop continues in a damaged process
}

Notice that the code is not careless. Its author wanted the worker to survive bad messages, which is a good goal for exceptions. The problem is that Throwable also includes errors after which survival is the wrong goal.

2The Decision: Fail Fast and Restart

The decision I would make is simple to state: after an OutOfMemoryError, the process ends and the orchestrator starts a new one. In Kubernetes or any similar platform, a restart takes seconds and brings back a process in a known good state, while other replicas carry the traffic. Compared with a damaged process that might serve wrong data for hours, the cost of a few failed in-flight requests is small.

The mechanism is in the JVM, not in application code. -XX:+ExitOnOutOfMemoryError makes the JVM exit on the first OutOfMemoryError, wherever it is thrown and whatever catch blocks exist, so no application code can swallow it. Together with -XX:+HeapDumpOnOutOfMemoryError, the dump is written first, so the evidence is kept. StackOverflowError has no equivalent flag, and its damage is usually more local, since the stack unwinds, so for it the rule is about catch blocks, below.

Step throughWhat happens to an Error in a service
  1. OutOfMemoryError thrownanywhere in any thread
  2. JVM flag ExitOnOutOfMemoryErrordump written, process exits
  3. Orchestrator restartsfresh process, known state
  4. Restart metric and alertthe leak is still visible
  5. Other Errors reach a top-level handlerlog, then rethrow or exit, never continue

5 steps in order. Play them, or step through them one at a time.

3The One Place Catching Is Allowed

Banning every catch of Throwable would go too far, because some code genuinely must stand at the top of a thread: a thread's run method, a message listener container, a scheduler. At that level, catching Throwable to make sure the failure is logged before the thread dies is useful. So the rule is: catching Throwable or Error is forbidden in application code, except in a small number of approved top-level handlers, and those handlers log and then rethrow or exit.

Below that level, code catches Exception, or better, the specific exceptions it can handle. A worker loop that should survive bad messages catches Exception, which still covers every RuntimeException and checked exception, and lets Errors pass.

Java
// Approved top-level handler, provided by the shared library
public final class FatalErrorHandler {
public static void handle(Throwable t) {
if (t instanceof VirtualMachineError) {
try { log.error("Fatal JVM error, exiting", t); } catch (Throwable ignored) { }
Runtime.getRuntime().halt(1); // exit now; the orchestrator restarts us
}
if (t instanceof Error e) throw e; // other Errors: never continue
}
}
// Worker loop in application code
while (running) {
try {
handle(queue.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} catch (Exception e) { // bad messages are survivable; Errors are not caught here
log.error("Handler failed for one message", e);
}
}

Notice the use of Runtime.halt rather than System.exit in the fatal path. System.exit runs shutdown hooks, which in a damaged process may block on a lock held by a dead thread; halt ends the process immediately. The thread's default uncaught exception handler can call the same handler, so errors that escape every catch also lead to a clean exit.

4Enforcing It Across the Fleet

A rule that lives only in a guide will be broken by the next new hire. So we enforce it in three places. Static analysis in CI: Sonar has a rule against catching Throwable and Error, and PMD and Error Prone have similar checks (check the rule names in your version). We turn it on as a build failure for new code and allow it only in the approved handler class, through a narrow suppression. The shared service template and base image: the JVM flags are set there, so every new service starts with them and existing services get them on their next image update. And code review: the reviewer checklist includes a line about broad catches.

For the existing code, we run the rule in report mode first. Across a large fleet this might find a few hundred catches of Throwable. Most are in worker loops and can be changed to catch Exception mechanically; a few are in genuine top-level handlers and move to the shared handler. We track the count per repository on a dashboard until it reaches zero.

5Making Sure Restarts Do Not Hide Leaks

Fail fast has one risk: a service with a slow memory leak now restarts every few days, quietly, and nobody fixes the leak. So the same decision includes monitoring. We count OOM restarts per service, from the container's last termination reason and exit code, and alert: a ticket for one OOM restart in a week, a page for several in an hour. We also alert earlier on heap usage after garbage collection trending upward and on GC time, so leaks are found before the first restart.

The heap dump from each restart goes to protected storage, and the owning team is expected to analyse it. A quarterly review of restart counts across the fleet shows which services rely on restarts as a crutch, and those get dedicated time to fix the cause.

6Follow-up questions

Isn't restarting worse for users than continuing?

Only in the short term. A restart fails the requests in flight on one replica, which clients can retry. A damaged process can fail or corrupt requests for hours and is much harder to diagnose, because the original error is long gone by the time someone looks.

What about StackOverflowError from one bad request?

The stack unwinds and the thread can usually carry on, so the damage is often limited. But it still ran into an arbitrary point in the code, so it should never be caught and ignored in business code. We let it reach the top-level handler, which logs it and fails the request, and we fix the recursion that caused it.

7Conclusion

In this answer, we saw that after OutOfMemoryError and similar errors a JVM may have lost threads, held locks or half-updated data, so broad catch blocks that keep it running cause long, confusing incidents. The organization-wide decision is to fail fast with -XX:+ExitOnOutOfMemoryError and let the orchestrator restart, to forbid catching Throwable or Error except in approved top-level handlers that log and rethrow or exit, to enforce this with static analysis and the shared service template, and to track restarts and memory alerts so restarts never hide a leak.

What to say in the interviewAbout 90 seconds aloud

Open with

The root problem is that after an OutOfMemoryError, and sometimes a StackOverflowError, the process cannot be trusted. These errors can hit any thread at almost any instruction, so a thread may have died halfway through an update, a lock may be held forever, or a background thread like a pool's housekeeper or a consumer heartbeat may be gone.

Then, if they want more

Broad catches of Throwable in worker loops swallow the error, and the service keeps passing health checks while broken.

So the decision I would make for the whole organization is fail fast: the standard base image runs with ExitOnOutOfMemoryError and HeapDumpOnOutOfMemoryError, so the JVM writes a dump and exits no matter what catch blocks exist, and the orchestrator starts a clean process.

In code, catching Throwable or Error is forbidden except in a few approved top-level handlers in a shared library, which log, and then rethrow or halt the process. Ordinary loops catch Exception.

I enforce it with a Sonar or Error Prone rule that fails the build, with a narrow suppression only for the approved handler, and with the service template, and I clean up existing code from a report first.

Finally, I make sure restarts do not hide leaks: we alert on OOM restarts and on rising heap after GC, and teams analyse the dumps.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Over several years your fleet has had recurring incidents where services kept running in...": https://scrivio-interview-library.netlify.app/java/exceptions/c26c23c56e/