Custom Exceptions in Java
A custom exception is a class that extends Exception, making it checked, or RuntimeException, making it unchecked, created specifically to represent a problem particular to a given program's domain — InsufficientFundsException communicates far more clearly than a generic IllegalStateException ever could about exactly what went wrong in a banking application. Defining one is usually just a small class with one or more constructors that call super(message) to set the exception's descriptive text, though it can carry extra fields too, like the specific account or amount involved.
Whether to extend Exception or RuntimeException for a custom exception comes down to the same checked-versus-unchecked judgment call as any other exception. If calling code can reasonably be expected to anticipate and specifically handle this condition, checked is often the better fit; if it represents a deeper misuse or bug, unchecked usually fits better.
Extending Exception or RuntimeException
Determines whether the new custom exception is checked or unchecked, exactly like any built-in exception.
A descriptive class name
Communicates specifically what went wrong, more clearly than a generic built-in exception type could.
A constructor calling super(message)
Passes the descriptive text up to Exception's own constructor, so getMessage() works correctly on the new type.
Extra fields for structured detail
A custom exception can carry more than just a message, like the specific value that caused the problem.
Choosing checked or unchecked
Follows the same judgment as any exception: can callers reasonably anticipate and handle this, or does it represent a deeper bug?
class InsufficientFundsException extends Exception { InsufficientFundsException(String message) { super(message); }} public class CustomExceptionDemo { static void withdraw(double balance, double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException("Cannot withdraw " + amount + " from balance " + balance); } System.out.println("Withdrawal successful"); } public static void main(String[] args) { try { withdraw(100, 150); } catch (InsufficientFundsException e) { System.out.println("Caught: " + e.getMessage()); } }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.