Custom Exception in Java

In Java, custom exceptions are exceptions that are created by the programmer to handle specific exceptional conditions in a program that are not covered by the built-in exceptions in Java. Custom exceptions can be useful when a program needs to handle specific types of exceptional conditions in a more fine-grained way, and the built-in exceptions are not sufficient for this purpose.

To create a custom exception in Java, we can create a new class that extends the Exception class or any of its subclasses, such as RuntimeException. The custom exception class should include a constructor that takes a String parameter that represents the message associated with the exception.

Here's an example of how to create a custom exception class in Java:

                
    public class CustomException extends Exception {
        public CustomException(String message) {
            super(message);
        }
    }
                
            

In this example, we have created a custom exception class called CustomException that extends the Exception class. The class includes a constructor that takes a String parameter representing the message associated with the exception.

Once we have created a custom exception class, we can use it in our program to handle specific exceptional conditions. Here's an example of how to use a custom exception in Java:

                
    public class Example {
        public static void main(String[] args) {
            try {
                int num = -1;
                if (num < 0) {
                    throw new CustomException("Number cannot be negative");
                }
            } catch (CustomException e) {
                System.out.println(e.getMessage());
            }
        }
    }
                
            

In this example, we have a main() method that throws an instance of CustomException if the value of num is less than 0. The exception is caught and handled in the catch block by printing the message associated with the exception object.

Custom exceptions can be very useful when a program needs to handle specific types of exceptional conditions that are not covered by the built-in exceptions in Java. They allow for more fine-grained exception handling and can make programs more robust and reliable.