Course contentsShow
← Java
Lesson 816 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

Constructors: Message, Cause, and Both

Implement standard exception constructors: default, message-only, cause-only, and message-with-cause patterns.

Constructors: Message, Cause, and Both

You'll learn how to implement the four standard constructors that every well-designed custom exception should provide.

The Standard Exception Constructor Pattern

When you create a custom exception, you should follow Java's established pattern by providing four constructors. Think of these as "communication channels" that let your exception explain what went wrong (the message) and why it happened (the cause—another exception).

The Four Standard Constructors

1. Default (no-argument) constructor:

public class InsufficientFundsException extends Exception {
    public InsufficientFundsException() {
        super();
    }
}

2. Message-only constructor:

public InsufficientFundsException(String message) {
    super(message);
}

3. Cause-only constructor:

public InsufficientFundsException(Throwable cause) {
    super(cause);
}

4. Message-with-cause constructor:

public InsufficientFundsException(String message, Throwable cause) {
    super(message, cause);
}

Why All Four?

Each constructor serves a different need:

  • Default: Quick throws when no details are needed
  • Message: Explain the specific problem in human-readable form
  • Cause: Wrap a lower-level exception (like IOException) as the root cause
  • Both: Provide your own explanation while preserving the original exception

The message-with-cause constructor is particularly powerful for exception chaining—when something goes wrong in a database layer, you can wrap that SQLException in your custom DataAccessException with a clearer message.

Key Takeaway: Always implement all four standard constructors in custom exceptions—default, message-only, cause-only, and message-with-cause—to give callers flexibility in how they create and throw your exception.