Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a custom unchecked exception OrderNotFoundException that carries the order ID and supports chaining. What constructors should it have?

OrderNotFoundException should extend RuntimeException, keep the order ID in a final field with an accessor, and offer at least two constructors: one taking the ID, and one taking the ID and a cause, with the first delegating to the second. Every constructor builds the message from the ID and passes the cause to super, so the ID and the original exception are never lost.

Why this question is asked

Custom exceptions are one of the first things we write in a real service, and they are easy to get subtly wrong: a missing cause constructor that forces callers to drop the original exception, or a message that holds the only copy of the ID, so handlers have to parse strings. Interviewers ask this to see whether we design an exception as a small, useful object rather than just a name. In this answer, we will recap checked and unchecked exceptions and chaining, write the class step by step, see how it is used and handled, and finish with the serialization detail that catches people out.

1A Quick Recap of Unchecked Exceptions and Chaining

Java has two families of exceptions. Checked exceptions extend Exception, and the compiler forces every caller to catch them or declare them with throws. Unchecked exceptions extend RuntimeException, and callers are free to let them pass. "Order not found" is something most callers cannot fix locally; they want it to travel up to a handler that turns it into a 404 response. That is why an unchecked exception is the usual choice here, and why most modern frameworks, Spring included, use unchecked exceptions.

Chaining means one exception holds another as its cause. When a repository call fails with, say, a database exception, and we throw our own exception in response, passing the original as the cause keeps its type, message and stack trace. Logs then show our exception followed by a Caused by: section with the original.

2Writing the Class

Here is the class. Each part has a reason, which we go through below.

Java
public class OrderNotFoundException extends RuntimeException {
private final String orderId;
public OrderNotFoundException(String orderId) {
this(orderId, null); // one path builds every instance
}
public OrderNotFoundException(String orderId, Throwable cause) {
super("Order not found: " + orderId, cause); // message and cause go to RuntimeException
this.orderId = orderId;
}
public String orderId() {
return orderId;
}
}

The ID lives in a final field. This is the most important design choice: handlers, metrics and tests can read ex.orderId() directly instead of parsing it out of the message. Messages are for people and may change wording; fields are for code and stay stable.

Notice that the one-argument constructor calls this(orderId, null). The reason is that all construction goes through one place, so the message format and the field assignment cannot drift apart between constructors. Passing null as the cause is fine: it simply means there is no underlying exception.

The second constructor accepts a cause. We always offer one, even if today nobody needs it, because the day someone catches a lower-level exception and throws ours, a missing cause constructor tempts them to drop the original. With this constructor they write new OrderNotFoundException(id, e) and the chain stays intact.

3Using It and Seeing the Result

Here are the two typical ways the exception is thrown, and what a handler sees.

Java
Order find(String id) {
return repository.findById(id)
.orElseThrow(() -> new OrderNotFoundException(id));
}
Order findInArchive(String id) {
try {
return archiveClient.fetch(id);
} catch (ArchiveMissException e) {
throw new OrderNotFoundException(id, e); // keeps the original as the cause
}
}
try {
find("A-17");
} catch (OrderNotFoundException e) {
System.out.println(e.getMessage()); // Order not found: A-17
System.out.println(e.orderId()); // A-17
System.out.println(e.getCause()); // null
}
Constructor choices and what they keep
ConstructorMessageID fieldCause
(String orderId)Order not found: A-17A-17none
(String orderId, Throwable cause)Order not found: A-17A-17original exception
Only (String message), no ID fieldwhatever the caller wrotelostlost
The last row is the common mistake: the ID exists only inside free text and the cause cannot be kept.

In the second method, the log would show OrderNotFoundException: Order not found: A-17 followed by Caused by: ArchiveMissException with its own trace. That is exactly what someone debugging needs. In a Spring application, a @RestControllerAdvice method can catch OrderNotFoundException and build a 404 problem response, using e.orderId() to fill a structured field.

4Optional Extras and When They Help

Throwable offers a few more constructors. The four-argument one, (message, cause, enableSuppression, writableStackTrace), lets an exception skip collecting its stack trace, which saves time when an exception is thrown very often. For a not-found exception that is thrown on a normal lookup path, some teams do this, but it removes the stack trace from logs, so we only do it when profiling shows the cost matters.

We might also be tempted to add a no-argument constructor or one taking only a message. For a domain exception like this one, both are a step backwards, because they allow instances without an order ID. Keeping the constructor list small is part of the design.

Since Java 16 we could not make this a record, because records cannot extend classes, but the accessor name orderId() follows the same style as record accessors, which reads naturally in modern code.

5The Serialization Detail

Throwable implements Serializable, so every exception is serializable by inheritance. That matters when exceptions cross Java serialization, for example in older RMI-based systems, some distributed caches, or session replication. A String field is fine. But if we added a field holding a non-serializable object, such as a database entity or a connection, serializing the exception would fail with NotSerializableException at the worst moment: while reporting another failure.

So we keep context fields to simple values such as strings, numbers and enums, mark anything else transient, and declare a serialVersionUID if the exception is serialized across versions. In most REST services exceptions never leave the JVM in serialized form, but the habit costs nothing.

6Follow-up questions

Should OrderNotFoundException be checked instead?

Usually not. A checked exception would force every method between the repository and the controller to declare or catch it, even though none of them can do anything useful. Checked exceptions make sense when the immediate caller can reasonably recover, such as choosing another file when one is missing. For a missing order that becomes a 404, unchecked is the better fit.

Why not just use a generic NotFoundException with a message?

A generic class can work as a base, but a specific subclass lets handlers and tests react to this case precisely and carries a typed field. A good compromise is a small hierarchy: a NotFoundException base that the web layer maps to 404, with OrderNotFoundException extending it and adding orderId.

Is it a problem that getMessage() includes the order ID?

An order ID is usually fine. The rule is never to put secrets or personal data, such as passwords, card numbers or email addresses, into exception messages, because messages end up in logs and sometimes in client responses. If the identifier were sensitive, we would keep it in the field and leave it out of the message.

7Conclusion

In this answer, we wrote OrderNotFoundException as an unchecked exception with a final orderId field and accessor, a constructor taking the ID that delegates to one taking the ID and a cause, and a message built in one place. We saw why structured context belongs in fields rather than only in the message, why a cause constructor should always exist, and why fields must stay serializable because every Throwable is Serializable.

What to say in the interviewAbout 80 seconds aloud

Open with

I would make it extend RuntimeException, because callers usually cannot recover from a missing order and it should travel up to a handler that returns a 404. It has a private final String orderId with an accessor, orderId().

Then, if they want more

I give it two constructors: one taking the order ID, which just calls this(orderId, null), and one taking the ID and a Throwable cause, which calls super with a message like Order not found plus the ID, and the cause, and then sets the field. Having every constructor go through one path keeps the message and the field consistent.

The cause constructor matters because whenever someone catches a lower-level exception and throws ours, they can pass the original, and the log keeps its type and stack trace under Caused by. I keep the ID in a field rather than only in the message so handlers and metrics can read it without parsing text.

I would not add a message-only constructor, because that allows instances without an ID. Finally, since every Throwable is Serializable, any context fields should be simple serializable values, or transient, in case the exception ever crosses Java serialization.

About this answer

Last updated
12 November 2026
Versions it names
Java 16
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 "Write a custom unchecked exception OrderNotFoundException that carries the order ID and...": https://scrivio-interview-library.netlify.app/java/exceptions/93ea58c5d7/