Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

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?

Use standard JDK exceptions such as IllegalArgumentException, IllegalStateException and NullPointerException for programming errors, so callers handle them like any other Java code. Use a small family of custom exceptions, carrying stable error codes, for domain and integration failures that callers may want to handle. Treat the exceptions a method throws as part of its public API: document them, wrap third-party exceptions instead of leaking them, and protect the contract with semantic versioning and automated compatibility checks such as japicmp or revapi.

Why this question is asked

When one library sits inside 80 services, its exceptions stop being an implementation detail. Somewhere in those services, someone has written a catch block, a retry rule, an HTTP status mapping or an alert that depends on exactly which exception the library throws. Change it carelessly and a service that worked yesterday starts returning 500 errors after a routine upgrade, with no compile error to warn anyone. Interviewers ask this question to see whether we think of exceptions as part of an API contract. In this answer, we will separate the two kinds of failure a library reports, decide which exception types to use for each, look at error codes and wrapping, and then see how to keep those choices stable across versions.

1Two Kinds of Failure a Library Reports

Every failure a library reports falls into one of two groups. The first is a programming error by the caller: they passed a null where a value was required, a negative page size, or they called close() twice. Nothing at run time can fix this; the caller's code must change. The second group is a real-world failure the caller may want to handle: an account was not found, a payment was declined, the downstream service timed out. Correct code still meets these, and a caller might retry, show a message, or choose a fallback.

The two groups need different exception types because callers treat them differently. Nobody writes catch (IllegalArgumentException e) to recover; they fix the bug. But many callers will write catch (PaymentDeclinedException e) to show a message to a customer.

Which exception type fits which failure
SituationExceptionWhy
Required argument is nullNullPointerException (Objects.requireNonNull)Programming error, every Java developer knows it
Argument out of rangeIllegalArgumentExceptionCaller must fix the call
Method called in the wrong stateIllegalStateExceptionCaller must fix the order of calls
Operation not supported by this implementationUnsupportedOperationExceptionStandard JDK meaning
Account not found, payment declinedAcmeException subclass with codeDomain outcome the caller may handle
Downstream timeout or connection failureAcmeIntegrationException with codeCallers may retry; cause preserved
Standard types for bugs, a small custom family for outcomes callers can act on.

2Standard Exceptions for Programming Errors

For programming errors, standard JDK exceptions are the right choice. Every developer in all 80 services already knows what IllegalArgumentException means, every framework already maps it sensibly, and callers need no library-specific import to deal with it. A custom InvalidAcmeArgumentException adds nothing except one more type to learn.

Java
public Page<Order> findOrders(CustomerId customer, int pageSize) {
Objects.requireNonNull(customer, "customer"); // NullPointerException: customer
if (pageSize < 1 || pageSize > 500) {
throw new IllegalArgumentException("pageSize must be 1..500, was " + pageSize);
}
...
}

Notice that the message names the parameter and the bad value. That costs nothing and saves someone in another team an hour of guessing.

3Custom Exceptions With Stable Error Codes

For outcomes callers can act on, we define a small hierarchy under one base class. A shallow tree is easier to use than a deep one: callers can catch the base type to handle everything from the library, or a specific subtype for the cases they care about. We make the base class unchecked, extending RuntimeException, because most callers in a Spring service will let these flow to a global handler, and checked exceptions would force every layer to declare them.

The most important field is an error code. Class names and messages change during refactoring; a code such as ACME-PAY-002 is a promise. Services log it, dashboards group by it, API responses return it, and support teams search for it. Once published, a code keeps its meaning forever, and a retired code is never reused.

Java
public class AcmeException extends RuntimeException {
private final ErrorCode code;
public AcmeException(ErrorCode code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public ErrorCode code() { return code; }
}
public enum ErrorCode {
ACCOUNT_NOT_FOUND("ACME-ACC-001"),
PAYMENT_DECLINED("ACME-PAY-002"),
UPSTREAM_TIMEOUT("ACME-INT-003"); // never renumber, never reuse
...
}
public class PaymentDeclinedException extends AcmeException { ... }

An enum works well inside the library, but notice the string value. Services persist and compare the string, so adding new enum constants in a minor release is safe, while renaming or removing one is a breaking change.

4Wrapping Third-Party Exceptions Instead of Leaking Them

Suppose the library uses an HTTP client internally and lets its exceptions escape. Now 80 services catch that client's exception type. When we switch HTTP clients, or the client renames its exception in a major version, every one of those catch blocks breaks or, worse, silently stops matching. The library's internals have leaked into its API.

So at the library boundary we catch third-party exceptions and wrap them in our own type, always passing the original as the cause. Cause chaining keeps the full original stack trace for debugging, while the type callers depend on stays ours.

Java
try {
return client.send(request, BodyHandlers.ofString());
} catch (HttpTimeoutException e) {
throw new AcmeIntegrationException(ErrorCode.UPSTREAM_TIMEOUT,
"payment gateway did not answer within 2s", e); // cause preserved
} catch (IOException e) {
throw new AcmeIntegrationException(ErrorCode.UPSTREAM_UNAVAILABLE, "payment gateway unreachable", e);
}

5Exceptions Are Part of the API Contract

Because callers write code against our exceptions, we document them with @throws in the Javadoc of every public method, including unchecked ones. The compiler does not force us to declare unchecked exceptions, but the documentation is what tells a caller which cases they can handle.

Then we treat changes to that list like changes to a method signature. Throwing a new subclass of an exception we already document is usually safe, because existing catch blocks still match. Throwing a different type, moving a type to another package, or changing which code a failure reports is a breaking change, even though every service still compiles. For a checked exception the compiler at least notices; for unchecked ones nothing does, which is exactly why we need process.

6Keeping Decisions Stable Across Versions

We publish the library with semantic versioning: patch releases fix bugs, minor releases add things without breaking callers, and major releases are the only place breaking changes are allowed. That gives the 80 teams a simple rule for upgrades.

Rules only hold if a machine checks them. We add an API compatibility tool such as japicmp or revapi to the build. It compares the new jar with the last released one and fails the build on binary or source incompatible changes, such as a removed public class or a method that now declares an extra checked exception. These tools cannot see behaviour, so we add contract tests that assert which exception type and error code each documented failure produces. A refactoring that accidentally turns PaymentDeclinedException into a plain AcmeException then fails a test instead of 80 deployments.

Step throughA release passes through the compatibility gate
  1. Build the new library jar
  2. Compare with last releasejapicmp or revapi
  3. Incompatible API change?
    YesAllowed only in a major versionNoContinue
  4. Run exception contract teststype and error code for each documented failure
  5. Contract changed?
    YesFail the build or bump majorNoPublish the release

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

7Follow-up questions

Should the custom base exception be checked or unchecked?

For a library used by many Spring services, unchecked is usually better. Most failures are handled once, at a boundary such as a @ControllerAdvice or a message listener, and checked exceptions would force every intermediate layer to declare or wrap them. Checked exceptions make sense for a narrow API where the caller genuinely must decide at the call site, but adding or removing a checked exception later is itself a source-breaking change, so the choice is hard to reverse.

How do services map these exceptions to HTTP responses?

We can ship an optional Spring module in the library with a @ControllerAdvice that turns AcmeException into a ProblemDetail response, using the error code as a property and a status chosen per code. Services that want different behaviour simply do not import that module. Keeping the mapping by code rather than by class name means it survives refactoring.

What about exceptions from libraries we expose on purpose, like Jackson?

If a type from another library already appears in our public method signatures, its exceptions are effectively part of our API too, and we accept that coupling consciously and document it. The rule against leaking applies to dependencies the caller should not need to know about, which is most of them.

8Conclusion

In this answer, we separated programming errors, which get standard JDK exceptions such as IllegalArgumentException and IllegalStateException, from domain and integration failures, which get a small custom hierarchy with stable error codes. We wrapped third-party exceptions with cause chaining so they never leak into the API, documented every thrown exception, and treated changes to them as breaking changes. Finally, we kept those decisions stable with semantic versioning, japicmp or revapi in the build, and contract tests for the behaviour those tools cannot see.

What to say in the interviewAbout 80 seconds aloud

Open with

I split failures into two kinds. Programming errors, like a null argument, an out-of-range value or a call in the wrong state, get standard JDK exceptions: NullPointerException through Objects.requireNonNull, IllegalArgumentException, IllegalStateException.

Then, if they want more

Every developer already knows them and no caller needs library-specific handling.

Failures that correct code can still meet and that callers may handle, like a declined payment or a downstream timeout, get a small custom hierarchy under one unchecked base exception, and each carries an error code that is stable forever; services log it, alert on it and return it in API responses, so I never rename or reuse a code.

At the library boundary I wrap third-party exceptions in our own types with the original as the cause, so a change of HTTP client does not break 80 catch blocks. I document every exception with @throws, because thrown exceptions are part of the contract and changing them is a breaking change even when everything still compiles.

To keep it stable I use semantic versioning, run japicmp or revapi against the last release in the build, and add contract tests that assert the exception type and code for each documented failure, since the tools cannot see behaviour.

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 "In a shared library used by 80 services, how should you choose between standard JDK...": https://scrivio-interview-library.netlify.app/java/exceptions/32899f6095/