Java Custom Exception Classes - Advanced Guide

What are Custom Exceptions in Java?

Custom Exceptions wahi hote hain jo aap apni specific application ki zaroorat ke hisab se banaate hain. Ye standard Java exceptions ki jagah ya unke alawa extra information dene ke liye use hote hain.

Creating Custom Exception Classes - Steps

Example: Custom Checked Exception Class

/**
 * Exception thrown when an invalid age is provided.
 */
public class InvalidAgeException extends Exception {
    private final int age;

    public InvalidAgeException(String message, int age) {
        super(message);
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

Using the Custom Exception

Custom exception ko throw karne aur catch karne ka example:

public class Registration {
    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above.", age);
        }
    }
    public static void main(String[] args) {
        try {
            validateAge(16);
        } catch (InvalidAgeException e) {
            System.out.println("Exception caught: " + e.getMessage());
            System.out.println("Invalid age provided: " + e.getAge());
        }
        System.out.println("Program continues...");
    }
}

Best Practices for Custom Exceptions

When to Use Custom Exceptions?

Jab aapko kisi unique error state ko represent karna hota hai jise Java ke built-in exceptions se achhi tarah handle nahi kiya ja sakta tab custom exception bana ke use karna chahiye. Yeh code readability aur maintainability badhata hai.