In the previous lesson we saw how to throw exceptions.
Creating your own exception class
It is possible to create an exception class of your own, if you can't find an appropriate Java supplied one to use. As an example, in a later section you will develop a user interface where the user can make entries onto various forms. If the user makes an invalid entry, you could throw an exception in order to trigger an error message, informing the user of the error so that it can be corrected. You can create your own exception classes simply by inheriting from one of the base Java supplied classes, as follows:
- For a checked exception type, extend
Exceptionor one of its checked[1] subclasses - For an unchecked exception type, extend
RuntimeExceptionor one of its subclasses
Because validation is a user recoverable situation you will create a new checked exception class. In package virtualzoo.core create a new Java class called ValidationException with the following code:
package virtualzoo.core;
public class ValidationException extends Exception {
public ValidationException(String message) {
super(message);
}
}
The constructor defined above requires a String message to be supplied which will contain the text of the validation error
You will make use of the ValidationException class in a later lesson.
In the next series of lessons you will learn about refactoring and utility classes.
Comments