All 15 Exceptions questions
More in Exceptions
Advertisement
Back to results for “Exception Handling”
Java › Exceptions

How do you create and throw a custom exception class, and what constructors should a well-designed custom exception typically provide?

Intermediate

Answer

A custom exception extends either Exception (checked) or RuntimeException (unchecked) as appropriate, and by convention should provide at least the standard four constructors mirroring Throwable's own (no-arg, message-only, message-plus-cause, and cause-only), ensuring the custom exception integrates smoothly with common exception-handling patterns (like wrapping-and-rethrowing with a cause) that calling code and libraries typically expect to be available on any well-behaved exception class.
public class InsufficientFundsException extends RuntimeException {
    public InsufficientFundsException() { super(); }
    public InsufficientFundsException(String message) { super(message); }
    public InsufficientFundsException(String message, Throwable cause) { super(message, cause); }
    public InsufficientFundsException(Throwable cause) { super(cause); }
}

throw new InsufficientFundsException("Account balance too low for withdrawal of $500");
Real-world example A banking application's InsufficientFundsException provides all four standard constructors, letting it be thrown with just a descriptive message in most cases, but also usable with a wrapped cause when the insufficient-funds determination itself resulted from a downstream service call failure.

Common follow-ups: Why is it considered good practice to provide all four standard constructors even if only one is currently used?;What naming convention (ending in 'Exception') helps make custom exception classes immediately recognizable in a codebase?