Definition
Custom exceptions in Java are user-defined exceptions created by extending the base Exception class (for checked exceptions) or RuntimeException class (for unchecked exceptions). These exceptions help handle specific error scenarios in a more descriptive and application-specific way.
Contents
Example
// Define a custom exception
class CustomException extends Exception {
public CustomException(String message) {
super(message); // Pass message to the superclass constructor
}
}
// Example usage
public class CustomExceptionExample {
// Method that throws the custom exception
public static void checkNumber(int number) throws CustomException {
if (number < 0) {
throw new CustomException("Number cannot be negative: " + number);
}
System.out.println("Valid number: " + number);
}
public static void main(String[] args) {
try {
checkNumber(5); // Valid case
checkNumber(-3); // This will throw CustomException
} catch (CustomException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Output
Valid number: 5
Caught Exception: Number cannot be negative: -3
Feature
- Custom Messages: Allow developers to define detailed error messages specific to the exception.
- Checked or Unchecked: Developers can choose whether the exception should be checked or unchecked based on the application’s needs.
- Inheritance: Custom exceptions integrate seamlessly with Java’s exception hierarchy.
- Centralized Error Handling: Simplifies debugging by categorizing specific types of errors.
Advantages
- Improved Readability: Provides descriptive and meaningful exception names, helping to understand the problem at a glance.
- Error-Specific Handling: Facilitates handling specific error scenarios distinct from generic exceptions.
- Encapsulation: Encapsulates error logic and conditions in one place, making the code modular and easier to maintain.
- Enhanced Debugging: Helps in debugging by clearly specifying the cause of the exception.
- Code Reusability: Custom exceptions can be reused across the application, promoting consistency in error handling.