Creating Custom Exceptions in Java
Fast recall
Quick revision
Core answer
RuntimeException for an unchecked application failure or Exception for a checked one. Give it a clear domain name and the constructors callers need, commonly message and message-plus-cause constructors that delegate to super. Add structured fields only when handlers use them.Whether you can define a well-formed custom exception with the standard constructor set and the right base class
Forgetting the (message, cause) constructor, or extending Throwable/Exception without a clear reason
Explain that a meaningful type name plus a cause constructor is what makes a custom exception worth creating over a generic one
Interview-ready guide
Interview answer
I create a custom exception by extending Exception for a checked API or RuntimeException for an unchecked one, then give it a domain-specific name. Constructors are not inherited, so I normally add a message constructor and a message-plus-cause constructor when the exception may wrap another failure.
The class usually needs no behavior. I add an immutable code or resource identifier only if a handler uses that structured context, and I avoid putting secrets or large mutable objects into an exception.
Creating Custom Exceptions in Java
Direct Answer
Create a custom exception by extending the exception type that matches the API contract—often RuntimeException for an unchecked application failure or Exception for a checked one. Give it a clear domain name and the constructors callers need, commonly message and message-plus-cause constructors that delegate to super. Add structured fields only when handlers use them.
Code Example
// Unchecked domain exception -- the common choice
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String message) {
super(message);
}
public InsufficientFundsException(String message, Throwable cause) {
super(message, cause); // preserve the underlying cause
}
}
// Usage -- the type name itself explains the failure
if (amount > balance) {
throw new InsufficientFundsException(
"withdrawal " + amount + " exceeds balance " + balance);
}
Extend Exception instead of RuntimeException if you want callers to be forced to handle it.
Common Mistakes & Pitfalls
- Omitting the
(message, cause)constructor — you can't chain a wrapped exception without it. - Extending
ThrowableorError— almost always wrong; extendRuntimeException/Exception. - Vague names —
MyExceptionsays nothing; name it for the domain failure. - Adding heavy logic — exceptions should carry information, not run business logic.
Check your understanding
Answer these without looking back at the article.
- When should a custom exception be checked vs unchecked?
- Why provide a cause constructor in a custom exception?
- What naming convention should custom exceptions follow?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.