If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, you can create your own custom exceptions, known as user-defined exceptions, by extending the existing exception classes. User-defined exceptions allow you to handle specific error conditions in your application and provide meaningful and customized error messages to users.
To create a user-defined exception, follow these steps:
Exception or one of its subclasses like RuntimeException).Here's an example of creating a user-defined exception:
javaCopy code
// User-defined exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Application class
public class CustomExceptionExample {
public static void main(String[] args) {
try {
int age = -5;
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative.");
}
System.out.println("Age: " + age);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
In this example, we create a custom exception called InvalidAgeException by extending the Exception class. The constructor of the custom exception takes a message as an argument and passes it to the superclass constructor using the super keyword.
In the main method, we throw the InvalidAgeException if the age is negative. When the exception is thrown, the control is transferred to the catch block that matches the InvalidAgeException, and the error message "Error: Age cannot be negative." is displayed.
User-defined exceptions allow you to tailor exception handling to the specific requirements of your application. By creating custom exception classes, you can provide better error reporting, more informative error messages, and specific exception handling logic that suits the needs of your application domain.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support