By Tony Bevis on Thursday, 12 October 2023
Category: Java

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:


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.

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

Related Posts

Leave Comments