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.
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.
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.
Exception
for checked custom exceptions.RuntimeException
for unchecked custom exceptions.Note: Use checked exceptions for recoverable conditions and unchecked exceptions for programming errors.
Mastering the switch-case logic in Java with examples.
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());
}
}
}
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);
}
}
Custom exceptions clearly indicate invalid input data scenarios.
Handle domain-specific errors like negative balances or invalid operations.
Express unique application rules and constraints with meaningful exceptions.
To provide more precise error information specific to the application domain.
By extending the Exception
class and defining constructors.
For programming errors or conditions that the caller cannot reasonably recover from.