Quick revision
The short answer
I would set five principles for shared libraries: exceptions are for unexpected failures and expected outcomes go in return types; exception types and error codes are part of the public API and follow compatibility rules; causes are always kept and messages never contain secrets; exceptions stay off hot paths, verified with profiling and JFR; and production data, the top exception types by count, is reviewed regularly to fix noisy or misused exceptions. The principles are checked over time with API compatibility checks, static analysis, benchmarks and a periodic review of real exception counts.
What to remember
In this answer, we set principles for exceptions in shared libraries: use them for unexpected failures and put expected outcomes in types; treat exception types and error codes as versioned public API; always keep causes and never put secrets in messages; keep exceptions off hot paths and measure with benchmarks and JFR, enabling the costly jdk.JavaExceptionThrow event only selectively. We checked them over time with compatibility tooling, static analysis and a regular review of the top exception types by count in production.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would set five principles for shared libraries: exceptions are for unexpected failures and expected outcomes go in return types; exception types and error codes are part of the public API and follow compatibility rules; causes are always kept and messages never contain secrets; exceptions stay off hot paths, verified with profiling and JFR; and production data, the top exception types by count, is reviewed regularly to fix noisy or misused exceptions. The principles are checked over time with API compatibility checks, static analysis, benchmarks and a periodic review of real exception counts.
Why this question is asked
A core library's exception design outlives the people who wrote it. Hundreds of services catch its exception types, match on its error codes and log its messages, so a careless choice made in an afternoon, a checked exception on a common call, an exception used to signal "not found", a message that includes the request body, becomes a cost paid by every team for years. Interviewers ask this to see whether a senior engineer can turn experience into principles that are clear, checkable and stable. In this answer, we will go through each principle with the reasoning behind it, and then describe how to check them over time so they do not quietly decay.
1Principle 1: Exceptions for Failures, Types for Outcomes
The first principle decides when an exception is the right tool at all. An exception is right when the caller usually cannot handle the situation locally and it should travel up to a central handler: a dependency is down, data is corrupt, our own code has a bug. It is wrong when the situation is a normal, expected result that the caller must handle, such as "no such user", "insufficient balance" or "token expired".
For expected outcomes the library returns them in the type: Optional for simple absence, a sealed result type with records for outcomes with detail. The reasons are both clarity and cost. The signature tells the caller what can happen, the compiler checks that each case is handled, and the library does not build a stack trace for something that happens thousands of times a minute.
2Principle 2: Exception Types and Codes Are Public API
Once a library is published, its exception types are part of its contract just as much as its method signatures. A caller who writes catch (RateLimitedException e) depends on that class existing, on its place in the hierarchy, and on the situations in which it is thrown. Error codes such as TOKEN_EXPIRED are matched by clients, dashboards and alert rules.
So they follow the library's compatibility rules. We document which exceptions each public method can throw and what they mean. Adding a new exception type or code is a minor change. Removing one, renaming one, moving it in the hierarchy, or throwing a different type in an existing situation is a breaking change, which goes through deprecation and a major version. Messages, by contrast, are explicitly not part of the contract and can be reworded freely, which is why codes exist.
| Change | Compatible? | Why |
|---|---|---|
| Add a new error code | yes | existing callers are unaffected |
| Add a new subclass of an existing type | yes | existing catch blocks still catch it |
| Reword a message | yes | messages are not part of the contract |
| Rename or remove an exception type | no | callers' catch blocks stop compiling |
| Throw a different type for the same situation | no | callers' handling silently changes |
| Make an unchecked exception checked | no | callers stop compiling |
3Principle 3: Always Keep Causes, Never Leak Secrets
Whenever library code translates a lower-level exception into its own type, it passes the original as the cause. Every exception constructor in the library accepts a cause, so there is never a reason to drop one. This is what lets an engineer read a log and see, at the bottom of the chain, the actual socket timeout or SQL error.
The second half is about what exceptions carry. Messages and context fields end up in logs, in error responses and sometimes in third-party monitoring tools. So library exceptions never include passwords, tokens, API keys, full request or response bodies, or personal data such as email addresses. If an identifier is needed for debugging, the library includes a safe reference, such as an internal ID or a hash.
4Principle 4: Keep Exceptions Off Hot Paths, and Measure
A shared library is called on the hottest paths of many services, so its use of exceptions affects their CPU budgets. The rule is that the normal, frequent paths do not throw. Checking first or returning a result is preferred, and if an exception type must exist for a frequent case, it is designed to be cheap, for example by skipping the stack trace with the writableStackTrace=false constructor, with that choice documented.
Claims about cost are checked, not assumed. Performance-sensitive library methods have JMH benchmarks in the build. In production, JDK Flight Recorder helps: the jdk.ExceptionStatistics event counts throwables cheaply, while jdk.JavaExceptionThrow records every exception with its stack trace but is off by default because it is costly, so we enable it selectively and briefly, for example for a few minutes on one instance, to find where exceptions come from.
5Checking the Principles Over Time
Principles decay unless something checks them. For the API principle, a binary compatibility tool such as japicmp or Revapi runs on every library release and fails the build on removed or changed exception types, unless the version is a major one. For causes and messages, static analysis rules flag catch blocks that throw without passing the caught exception, and code review for the library uses a short checklist that includes a question about sensitive data in messages.
The most valuable check is production data. Every quarter, the owning team pulls the top exception types and codes by count across all services, from log aggregation and from error metrics tagged by type. This list is revealing. An exception thrown 50 million times a day is almost certainly being used for an expected outcome and should become a return type. A code that never appears may be dead. An exception that frequently reaches the generic 500 handler suggests a missing mapping. Each finding becomes a concrete change in the next library release, and the next review checks whether the numbers moved.
- Collect top exceptions by countlogs and error metrics across services
- Thrown extremely often?YesMove the case to a return type or cheap exceptionNoCheck the next one
- Reaching the generic 500 handler?YesAdd a code and a mappingNoCheck the next one
- Release the changewith compatibility rules and notes
- Compare counts next quarterdid the change work?
5 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Should a shared library ever throw checked exceptions?
Rarely. Checked exceptions force every caller to handle or declare them, which spreads through many services and works poorly with lambdas. They can make sense for a narrow, low-level API where callers genuinely can recover, but for most shared libraries unchecked exceptions with clear documentation and result types for expected outcomes are the better default.
How do you introduce these principles to an existing library?
By applying them to new APIs first and treating the existing ones as a migration. New methods return result types, existing methods that throw for expected outcomes get a new alternative and the old one is deprecated, and the compatibility tool makes sure nothing breaks by accident. The production data review shows which changes matter most.
Who decides when an exception type can be removed?
The library's owning team, through its normal versioning process, and only in a major version after a deprecation period. The release notes explain what replaced it, and the usage data from the review shows how many services are still affected before the removal is scheduled.
7Conclusion
In this answer, we set principles for exceptions in shared libraries: use them for unexpected failures and put expected outcomes in types; treat exception types and error codes as versioned public API; always keep causes and never put secrets in messages; keep exceptions off hot paths and measure with benchmarks and JFR, enabling the costly jdk.JavaExceptionThrow event only selectively. We checked them over time with compatibility tooling, static analysis and a regular review of the top exception types by count in production.
Open with
I would start from the fact that a core library's exceptions are used by hundreds of services for years, so the principles have to be few and checkable.
Then, if they want more
First, exceptions are for unexpected failures, like an outage or a bug; expected outcomes such as not found or insufficient balance go in return types, Optional or sealed results. Second, exception types and error codes are public API.
Adding is fine, but removing, renaming or throwing a different type for the same situation is a breaking change, so it goes through deprecation and a major version, and I enforce that with a compatibility checker like japicmp or Revapi in the release build. Messages are not part of the contract, which is why we have codes.
Third, causes are always kept and messages never carry secrets or personal data, because they end up in logs and responses; static analysis and review checklists cover that. Fourth, no exceptions on hot paths.
I would have JMH benchmarks for sensitive methods, and in production use JFR: exception statistics are cheap, and jdk.JavaExceptionThrow gives stacks but is off by default and costly, so I enable it briefly on one instance. Finally, every quarter we review the top exception types by count across services.
Something thrown millions of times a day is probably an expected outcome in disguise, and things reaching the generic 500 handler need a mapping.
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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "Exception design decisions in core libraries affect performance, debuggability and API...": https://scrivio-interview-library.netlify.app/java/exceptions/86a9856f4c/