❔ What is a Custom Exception?
A custom exception is a user-defined class that extends either:
Exception→ for checked exceptionsRuntimeException→ for unchecked exceptions
You create them when built-in exceptions are not descriptive or specific enough for your program’s needs.
💡 Real-Life Analogy
Imagine you're building a banking system.
Java doesn’t have InsufficientFundsException, so you create your own to make error handling clear and meaningful.
❗Creating a Custom Exception
1️⃣ Step 1: Define the Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}✅ This defines a checked exception because it extends Exception.
2️⃣ Step 2: Use the Exception with throw
public class Main {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
} else {
System.out.println("Eligible to vote");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
}Caught custom exception: Age must be 18 or above❗Custom Unchecked Exception (Optional)
If you don’t want Java to force you to handle the exception (like runtime ones), extend RuntimeException:
class TooManyAttemptsException extends RuntimeException {
public TooManyAttemptsException(String msg) {
super(msg);
}
}**Use just like above, but no need to declare with throws.
❔When to Use Custom Exceptions?
When built-in exceptions don’t convey the meaning
To make your code more readable and maintainable
For domain-specific errors (e.g.,
LowBalanceException,UserNotFoundException)
🧾 Recap Table
Feature | Checked Custom Exception | Unchecked Custom Exception |
|---|---|---|
Extend class |
|
|
Requires handling? | ✅ Yes (try-catch or throws) | ❌ No (optional handling) |
Use case | Critical app-level validation | Logical app bugs, optional handling |