Java Custom Exceptions
In Java, you can create your own custom exceptions to handle specific situations in your code. Custom exceptions
are created by extending the Exception class or one of its subclasses.
Creating a Custom Exception Class:
// Custom exception class
public class CustomException extends Exception {
public CustomException() {
super("This is a custom exception.");
}
public CustomException(String message) {
super(message);
}
}
Using Custom Exceptions:
public class CustomExceptionExample {
public static void main(String[] args) {
try {
// Simulating a situation that triggers the custom exception
validateAge(15);
} catch (CustomException e) {
// Handling the custom exception
System.out.println("Custom Exception: " + e.getMessage());
}
}
// Method that throws the custom exception
private static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or older.");
} else {
System.out.println("Age is valid.");
}
}
}
Note:
Custom exceptions are useful when you want to create meaningful and specific exceptions for your application. They allow you to handle exceptional cases in a way that makes sense for your business logic.