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

Extending RuntimeException for Unchecked Exceptions

Create custom unchecked exceptions by extending RuntimeException for programming errors and validation failures.

Extending RuntimeException for Unchecked Exceptions

What you'll learn: How to create your own custom unchecked exceptions by extending RuntimeException to signal programming errors and validation failures in your applications.

Why Extend RuntimeException?

While Java provides many built-in unchecked exceptions like IllegalArgumentException and IllegalStateException, sometimes you need more specific exceptions that describe problems unique to your application's domain. By extending RuntimeException, you create unchecked exceptions that don't require callers to catch them or declare them in throws clauses—perfect for signaling programming bugs or violations of business rules.

Creating Custom Unchecked Exceptions

The basic pattern is straightforward: create a class that extends RuntimeException and provide constructors that match the parent class:

public class InvalidAccountBalanceException extends RuntimeException {
    public InvalidAccountBalanceException() {
        super();
    }
    
    public InvalidAccountBalanceException(String message) {
        super(message);
    }
    
    public InvalidAccountBalanceException(String message, Throwable cause) {
        super(message, cause);
    }
}

Now you can throw this exception when your application detects an invalid condition:

public void withdraw(double amount) {
    if (amount > balance) {
        throw new InvalidAccountBalanceException(
            "Insufficient funds: attempted " + amount + ", balance is " + balance
        );
    }
    balance -= amount;
}

When to Use Custom RuntimeExceptions

Create custom unchecked exceptions for programming errors, contract violations, or situations where recovery is unlikely. They make your code self-documenting and allow specific catch blocks if needed, while not forcing callers to handle errors they can't realistically fix.

Key Takeaway: Extend RuntimeException to create custom unchecked exceptions for programming errors and validation failures specific to your domain—they inherit the unchecked nature, requiring no throws declarations while providing meaningful, application-specific error types.