Custom Exception Classes

Thinking

Sometimes built-in exceptions don't fully capture the specific error scenarios in your application.

Creating custom exception classes allows you to represent and handle application-specific error conditions clearly and effectively.

Description

Custom exceptions are user-defined classes that extend Exception or RuntimeException. They provide meaningful error messages and specialized handling for your application's unique cases.

Key Points:

  • Extend Exception for checked custom exceptions.
  • Extend RuntimeException for unchecked custom exceptions.
  • Add constructors to pass messages or other relevant data.

Note: Use checked exceptions for recoverable conditions and unchecked exceptions for programming errors.

Video Resources

Switch Statements

Mastering the switch-case logic in Java with examples.

Examples (code)

Creating a Checked Custom Exception


class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class CustomExceptionDemo {
    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or older.");
        }
        System.out.println("Age is valid.");
    }

    public static void main(String[] args) {
        try {
            validateAge(15);
        } catch (InvalidAgeException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}
  

Creating an Unchecked Custom Exception


class NegativeAmountException extends RuntimeException {
    public NegativeAmountException(String message) {
        super(message);
    }
}

public class UncheckedExceptionDemo {
    public static void withdraw(double amount) {
        if (amount < 0) {
            throw new NegativeAmountException("Amount cannot be negative.");
        }
        System.out.println("Withdrawal successful: $" + amount);
    }

    public static void main(String[] args) {
        withdraw(-100);
    }
}
  

Real-World Applications

User Input Validation

Custom exceptions clearly indicate invalid input data scenarios.

Financial Transactions

Handle domain-specific errors like negative balances or invalid operations.

Business Logic

Express unique application rules and constraints with meaningful exceptions.

Interview Questions

Q1: Why create custom exceptions?

Show Answer

To provide more precise error information specific to the application domain.

Q2: How do you create a checked custom exception?

Show Answer

By extending the Exception class and defining constructors.

Q3: When to use unchecked custom exceptions?

Show Answer

For programming errors or conditions that the caller cannot reasonably recover from.