Dremendo Tag Line

User-Defined Exception in Java

Exception Handling in Java

In this lesson, we will learn how to create and use a user-defined exception in java.

What is User-Defined Exception in Java?

A user-defined exception in Java is a custom exception class created by the programmer to handle specific errors or exceptional conditions in their code. It allows for more precise error handling and reporting instead of relying on built-in exception classes provided by the Java API. User-defined exceptions are created by extending the Exception class or an Exception subclass.

video-poster

How to Create a User-Defined Exception in Java

To create a user-defined exception, we need to create a class and extend it with the Exception class, for example.

A User-Defined Exception Class

class NumberRangeException extends Exception
{
	// default constructor
    public NumberRangeException()
    {
		// invoking the parameterized constructor of the
		// parent class Exception with custom message
        super("Invalid Number Range");
    }
}

In the above program, we created a user-defined exception class known as NumberRangeException by extending it with the Exception class.

After that, we created a default constructor in the class NumberRangeException. Inside it, we invoked the parameterized constructor of the parent class Exception with a custom exception message using the super keyword as shown in the above program.

How to Use the User-Defined Exception Class

To use the above-created user-defined exception class, we have to use it in a new class to raise our custom exception using the throws and throw keyword as shown below.

Example

class NumberRangeException extends Exception
{
    // default constructor
    public NumberRangeException()
    {
        // invoking the parameterized constructor of the
        // parent class Exception with custom message
        super("Invalid Number Range");
    }
}

class MyData
{
    public int sum(int n) throws NumberRangeException
    {
        int i,s=0;

        // condition that will raise a NumberRangeException
        // using the throw keyword
        if(n<0)
        {
            throw new NumberRangeException();
        }

        for(i=1; i<=n; i++)
        {
            s=s+i;
        }
        return s;
    }
}

public class TestException
{
    public static void main(String args[])
    {
        MyData x=new MyData();
        try
        {
            System.out.println(x.sum(-10));
        }
        catch(NumberRangeException e)
        {
            // printing the default message set in the
            // user-defined exception class
            System.out.println(e.getMessage());

            // printing our custom message
            System.out.println("Negative Number Not Allowed");
        }
    }
}

Output

Invalid Number Range
Negative Number Not Allowed

In the above program, we create a Java file with the name TestException that contains the main method.

In the same file, we created our user-defined exception class and a new class called MyData.

Inside the class MyData, we created a method sum followed by the throws keyword and the name of our user-defined exception class NumberRangeException.

The throws keyword is used with the function signature stating that the function will raise an exception.

In the method sum, we have raised our custom exception when the value of n is less than 0 using the throw keyword followed by the new keyword and the name of our custom exception class, as shown above.

The throw keyword is used inside a method to raise a custom exception object that can be caught and handled using a try-catch block.

The main method uses the try-catch statement to handle our custom exception in the program.