In Java, exceptions are events that disrupt the normal flow of a program. While Java provides a robust set of built-in exceptions, there are times when you may need to create your own custom exceptions. Custom exceptions allow developers to handle specific error scenarios that may not be covered by standard exceptions. This article presents three practical examples of custom exception classes in Java, each illustrating different use cases.
In a user registration system, it is crucial to validate user input. One common validation is ensuring that the user does not provide an invalid age, such as a negative number or an unreasonably high value. This example demonstrates how to create a custom exception for handling invalid age inputs.
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Method to validate age
public class UserRegistration {
public void registerUser(String name, int age) throws InvalidAgeException {
if (age < 0 || age > 120) {
throw new InvalidAgeException("Age must be between 0 and 120.");
}
// Proceed with registration logic
System.out.println("User registered: " + name + " with age " + age);
}
}
// Example usage
public class Main {
public static void main(String[] args) {
UserRegistration userReg = new UserRegistration();
try {
userReg.registerUser("Alice", -5);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage()); // Output: Age must be between 0 and 120.
}
}
}
In a banking application, it is essential to ensure that a user does not withdraw more money than they have in their account. This example creates a custom exception to handle insufficient funds during a withdrawal process.
// Custom exception class
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
// Banking class
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds: current balance is " + balance);
}
balance -= amount;
System.out.println("Withdrawal successful: new balance is " + balance);
}
}
// Example usage
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(100.0);
try {
account.withdraw(150.0);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage()); // Output: Insufficient funds: current balance is 100.0
}
}
}
When working with databases or data repositories, it’s common to encounter scenarios where a requested record does not exist. This example illustrates how to create a custom exception for handling cases when data is not found in the repository.
// Custom exception class
class DataNotFoundException extends Exception {
public DataNotFoundException(String message) {
super(message);
}
}
// Repository class
import java.util.HashMap;
import java.util.Map;
public class DataRepository {
private Map<Integer, String> dataStore = new HashMap<>();
public void addData(int id, String data) {
dataStore.put(id, data);
}
public String getData(int id) throws DataNotFoundException {
if (!dataStore.containsKey(id)) {
throw new DataNotFoundException("Data with ID " + id + " not found.");
}
return dataStore.get(id);
}
}
// Example usage
public class Main {
public static void main(String[] args) {
DataRepository repo = new DataRepository();
repo.addData(1, "Sample Data");
try {
System.out.println(repo.getData(2)); // Trying to access non-existing data
} catch (DataNotFoundException e) {
System.out.println(e.getMessage()); // Output: Data with ID 2 not found.
}
}
}
Custom exceptions in Java provide a powerful way to handle specific error conditions gracefully. By creating tailored exception classes, developers can improve code readability and maintainability while ensuring robust error handling in various applications.