Skip to main content
Course/Module 7/Topic 2 of 3Intermediate

Custom Exceptions & Throw

You can create your own exception classes to represent specific error conditions in your application. The 'throw' keyword lets you manually trigger exceptions, and 'throws' declares what exceptions a method might throw.

35 minBy Priygop TeamLast updated: Feb 2026

Custom Exceptions

Example
// Custom exception class
class InsufficientFundsException extends Exception {
    private double amount;
    private double balance;
    
    InsufficientFundsException(double amount, double balance) {
        super("Insufficient funds: tried to withdraw $" + amount + " but balance is $" + balance);
        this.amount = amount;
        this.balance = balance;
    }
    
    double getShortfall() {
        return amount - balance;
    }
}

class InvalidAgeException extends Exception {
    InvalidAgeException(int age) {
        super("Invalid age: " + age + ". Age must be between 0 and 150.");
    }
}

class Account {
    private String name;
    private double balance;
    
    Account(String name, double balance) {
        this.name = name;
        this.balance = balance;
    }
    
    // 'throws' declares this method might throw an exception
    void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount, balance);
        }
        balance -= amount;
        System.out.println("Withdrew $" + amount + " | Balance: $" + balance);
    }
    
    double getBalance() { return balance; }
}

public class CustomExceptionDemo {
    static void validateAge(int age) throws InvalidAgeException {
        if (age < 0 || age > 150) {
            throw new InvalidAgeException(age);
        }
        System.out.println("Valid age: " + age);
    }
    
    public static void main(String[] args) {
        Account acc = new Account("Alice", 1000);
        
        try {
            acc.withdraw(500);   // OK
            acc.withdraw(800);   // Too much!
        } catch (InsufficientFundsException e) {
            System.out.println("Error: " + e.getMessage());
            System.out.println("You need $" + e.getShortfall() + " more.");
        }
        
        // Test age validation
        int[] ages = {25, -5, 200, 30};
        for (int age : ages) {
            try {
                validateAge(age);
            } catch (InvalidAgeException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
}

Try It Yourself: Password Validator

Try It Yourself: Password ValidatorJava
Java Editor
✓ ValidTab = 2 spaces
Java|44 lines|1708 chars|✓ Valid syntax
UTF-8

Quick Quiz: Custom Exceptions

Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep