DEV Community

Cover image for Defining Custom Exception Classes
Paul Ngugi
Paul Ngugi

Posted on

Defining Custom Exception Classes

You can define a custom exception class by extending the java.lang.Exception class. Java provides quite a few exception classes. Use them whenever possible instead of defining your own exception classes. However, if you run into a problem that cannot be adequately described by the predefined exception classes, you can create your own exception class, derived from Exception or from a subclass of Exception, such as IOException.

In here, CircleWithException.java, the setRadius method throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler. In that case, you can define a custom exception class, as shown in the program below.

Image description

This custom exception class extends java.lang.Exception (line 1). The Exception class extends java.lang.Throwable. All the methods (e.g., getMessage(), toString(), and printStackTrace()) in Exception are inherited from Throwable. The Exception class contains four constructors. Among them, the following two constructors are often used:

Line 6 invokes the superclass’s constructor with a message. This message will be set in the exception object and can be obtained by invoking getMessage() on the object. Most exception classes in the Java API contain two constructors: a no-arg constructor and a constructor with a message parameter.

To create an InvalidRadiusException, you have to pass a radius. Therefore, the setRadius method in CircleWithException.java can be modified as shown in program below.

package demo;

public class TestCircleWithCustomException {

    public static void main(String[] args) {
        try {
            new CircleWithCustomException(5);
            new CircleWithCustomException(-5);
            new CircleWithCustomException(0);
        }
        catch(InvalidRadiusException ex) {
            System.out.println(ex);
        }

        System.out.println("Number of objects created: " + CircleWithCustomException.getNumberOfObjects());
    }

}

class CircleWithCustomException{
    /** The radius of the circle */
    private double radius;

    /** The number of objects created */
    private static int numberOfObjects = 0;

    /** Construct a circle with radius 1 */
    public CircleWithCustomException() throws InvalidRadiusException{
        this(1.0);
    }

    /** Construct a circle with a specified radius */
    public CircleWithCustomException(double newRadius) throws InvalidRadiusException {
        setRadius(newRadius);
        numberOfObjects++;
    }

    /** Return radius */
    public double getRadius() {
        return radius;
    }

    /** Set a new radius */
    public void setRadius(double newRadius) throws InvalidRadiusException{
        if(newRadius >= 0)
            radius = newRadius;
        else
            throw new InvalidRadiusException(newRadius);
    }

    /** return numberOfObjects */
    public static int getNumberOfObjects() {
        return numberOfObjects;
    }

    /** Return the area of this circle */
    public double findArea() {
        return radius * radius * 3.14159;
    }
}
Enter fullscreen mode Exit fullscreen mode

InvalidRadiusException: Invalid radius -5.0
Number of objects created: 1

The setRadius method in CircleWithCustomException throws an InvalidRadiusException when radius is negative (line 48). Since InvalidRadiusException is a checked exception, the setRadius method must declare it in the method header (line 44). Since the constructors for CircleWithCustomException invoke the setRadius method to a set a new radius and it may throw an InvalidRadiusException, the constructors are declared to throw InvalidRadiusException (lines 28, 33).

Invoking new CircleWithCustomException(-5) (line 8) throws an InvalidRadiusException, which is caught by the handler. The handler displays the radius in the exception object ex.

Can you define a custom exception class by extending RuntimeException? Yes, but it is not a good way to go, because it makes your custom exception unchecked. It is better to make a custom exception checked, so that the compiler can force these exceptions to be caught in your program.

Top comments (0)