Interview Q&A · Java · 4 questions in this topic
Custom Exceptions — Java Interview Q&A
When and how to model your own domain failures with clear exception types. Part of Exception Handling · 294 questions in the Java bank.
Custom exception types turn an ambiguous failure into a named, documented part of a method contract. Define one when the caller can act differently — retrying a payment, asking for another input, or surfacing a validation message — rather than when any RuntimeException would do. Keep the hierarchy shallow, name the type after the failure (InsufficientFundsException, not PaymentErrorException), and let the type carry the meaning while the message carries the detail. Constructors that accept a cause preserve the original stack trace when a lower-level failure is translated into a domain one.
What are user-defined exceptions?
Answer
User-defined exceptions are custom classes created to represent domain-specific failures such as an invalid account state or a failed business rule. Extending Exception makes the new type checked, while extending RuntimeException makes it unchecked. Well designed custom exceptions provide constructors for a message and a cause so callers get both context and the original failure.
Key points
- 1Extend Exception for a recoverable, checked failure; extend RuntimeException for a programming error callers may ignore.
- 2Give the class a message constructor and a message-plus-cause constructor so the original failure is never lost.
- 3Name the failure, not the layer: InsufficientFundsException reads better than PaymentServiceException.
Example
class InsufficientFundsException extends Exception { InsufficientFundsException(String msg) { super(msg); } InsufficientFundsException(String msg, Throwable cause) { super(msg, cause); } }
💡 Create a custom exception when callers need to handle one domain failure differently from generic IO or runtime errors.
Should a custom exception extend Exception or RuntimeException?
Answer
Extend Exception when callers can reasonably recover and you want the compiler to force them to handle it — a checked exception is part of the method contract. Extend RuntimeException when the failure is a programming error or an unrecoverable precondition, so callers are not forced into empty catch blocks. Never extend Error or Throwable directly: Error is reserved for JVM-level failures that applications are not expected to handle.
Key points
- 1Checked exceptions document a recoverable contract.
- 2Unchecked exceptions suit invalid arguments and broken invariants.
- 3Extending Error reserves it for serious JVM conditions.
- 4Both kinds should carry a message and, when wrapping, a cause.
How do you preserve the original cause when wrapping an exception?
Answer
Pass the original exception to the constructor: super(message, cause) or initCause for older classes. That keeps the full stack trace and lets tools print “Caused by:”. Wrapping without the cause destroys the evidence of what actually failed, and rethrowing a new exception with only a message is one of the most common debugging mistakes in production Java.
Key points
- 1Use super(message, cause) in the custom constructor.
- 2Never discard the cause when translating exception types.
- 3getCause() and the printed trace depend on it.
- 4Choose a message that adds context the cause does not have.
Example
try { loadConfig(); } catch (IOException e) { throw new ConfigException("cannot load config", e); }
What does creating an exception cost, and when should you avoid it?
Answer
Constructing an exception captures a stack trace, which walks the current stack and allocates an array of stack frames — expensive relative to ordinary control flow. Throwing thousands per second in a hot loop shows up in profiles. Use exceptions for exceptional conditions, validate with ordinary conditionals on the normal path, and when a failure is genuinely routine, consider a result type or a status return instead of an exception.
Key points
- 1fillInStackTrace walks and records the stack on every construction.
- 2A cached exception without a stack trace is possible but rarely advisable.
- 3Use conditionals for expected outcomes, exceptions for the unexpected.
- 4Never use exceptions to drive a loop’s normal exit.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission