In Java, an exception is an event that disrupts the normal flow of program execution. Java comes bundled with a set of built-in exceptions that can be thrown and caught, but in some cases, it might be necessary to create custom exceptions that are better suited to the needs of our application. In the post, we'll understand how we can create our own custom exceptions in detail.
Creating a Custom Exception
To create a custom exception, you need to extend the "Exception" class or any of its subclasses. The custom exception class should have a constructor that takes a string argument representing the error message. This message will be displayed when the exception is thrown.
For example, consider a scenario where an application requires to handle a specific exception when an invalid employee id is entered. To create this custom exception, we can define a class called InvalidEmployeeIdException, which extends the Exception class:
public class InvalidEmployeeIdException extends Exception {
public InvalidEmployeeIdException(String message) {
super(message);
}
}
Throwing a Custom Exception
To throw a custom exception, you use the “throw” keyword followed by a new instance of the exception. In the example below, we throw an InvalidEmployeeIdException if the employee id entered is less than 0:
public void validateEmployeeId(int id) throws InvalidEmployeeIdException {
if (id < 0) {
throw new InvalidEmployeeIdException("Invalid employee id: " + id);
}
}
Catching a Custom Exception
To catch a custom exception, you use a try-catch block. In the example below, we catch the InvalidEmployeeIdException and print a message:
try {
validateEmployeeId(-1);
} catch (InvalidEmployeeIdException e) {
System.out.println("Exception: " + e.getMessage());
}
And that's it!
In conclusion, custom exceptions are an effective way to handle specific error scenarios in Java applications. By creating custom exceptions, developers can provide meaningful error messages and handle them in a way that best suits the needs of the application. When creating custom exceptions, it is important to extend the Exception class or one of its subclasses and to provide a constructor method to initialize the exception with a message.