Java programming course: 7.3 Creating your own exception class

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 Exception or one of its checked[1] subclasses
  • For an unchecked exception type, extend RuntimeException or 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:

[1 ]Note that RuntimeException is a subclass of Exception so you should not extend that or any of RuntimeExceptions' sub-classes if you want your exception class to be checked.

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.

Next lesson: 8.1 Refactoring and utility classes


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image