In this chapter, you will learn how to define custom exceptions (user-defined exceptions) in Java with examples.
Table of Contents
- What are Custom Exceptions?
- Benefits of Using Custom Exceptions
- Creating Custom Exceptions
- Throwing Custom Exceptions
- Catching Custom Exceptions
- Example: Custom Checked Exception
- Example: Custom Unchecked Exception
- Best Practices for Custom Exceptions
- Real-World Analogy
- Conclusion
1. What are Custom Exceptions?
Custom exceptions are user-defined exception classes that extend the Exception
class or one of its subclasses. They allow you to create specific error conditions and messages that are more meaningful to your application.
By creating custom exceptions, you can handle errors more precisely and make your code more readable and maintainable.
2. Benefits of Using Custom Exceptions
- Clarity: Custom exceptions provide clear, specific error messages that make the code more understandable.
- Maintainability: They make it easier to manage and update error handling logic.
- Reusability: Custom exceptions can be reused across different parts of the application.
- Specificity: They allow you to distinguish between different error conditions and handle them accordingly.
3. Creating Custom Exceptions
Custom exceptions are created by extending the Exception
class (for checked exceptions) or the RuntimeException
class (for unchecked exceptions).
Syntax:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
4. Throwing Custom Exceptions
Custom exceptions are thrown using the throw
keyword, just like standard exceptions.
Example:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be at least 18.");
} else {
System.out.println("Access granted.");
}
}
}
Output:
Exception caught: Age must be at least 18.
5. Catching Custom Exceptions
Custom exceptions are caught using the catch
block, just like standard exceptions.
Example:
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be at least 18.");
} else {
System.out.println("Access granted.");
}
}
}
Output:
Exception caught: Age must be at least 18.
6. Example: Custom Checked Exception
Checked exceptions must be either caught or declared in the method signature using the throws
keyword.
Example:
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomCheckedExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught custom checked exception: " + e.getMessage());
}
}
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be at least 18.");
} else {
System.out.println("Access granted.");
}
}
}
Output:
Caught custom checked exception: Age must be at least 18.
7. Example: Custom Unchecked Exception
Unchecked exceptions extend the RuntimeException
class and do not need to be declared in the method signature.
Example:
public class InvalidAgeRuntimeException extends RuntimeException {
public InvalidAgeRuntimeException(String message) {
super(message);
}
}
public class CustomUncheckedExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeRuntimeException e) {
System.out.println("Caught custom unchecked exception: " + e.getMessage());
}
}
static void validateAge(int age) {
if (age < 18) {
throw new InvalidAgeRuntimeException("Age must be at least 18.");
} else {
System.out.println("Access granted.");
}
}
}
Output:
Caught custom unchecked exception: Age must be at least 18.
8. Best Practices for Custom Exceptions
- Meaningful Names: Give your custom exceptions meaningful names that clearly describe the error condition.
- Specific Messages: Provide detailed and specific error messages.
- Documentation: Document your custom exceptions to explain when and why they should be used.
- Inheritance: Use inheritance to create a hierarchy of exceptions if needed, making your error handling more flexible.
- Avoid Overuse: Use custom exceptions sparingly and only when standard exceptions are not sufficient.
9. Real-World Analogy
Consider a scenario where you are handling various types of errors in a library system:
- Standard Exceptions: Handle common errors like book not found (FileNotFoundException).
- Custom Exceptions: Handle specific errors like invalid library card (InvalidLibraryCardException) or overdue book (OverdueBookException).
10. Conclusion
Custom exceptions in Java provide a way to define specific error conditions and messages tailored to your application’s needs. By creating custom exceptions, you can handle errors more precisely and make your code more readable and maintainable. Following best practices for custom exceptions will help you write robust and understandable Java programs.