Write a Java Program to Create custom exception

Java is an object-oriented programming language that supports exception handling.

Exceptions are objects that represent errors or unexpected situations that occur during program execution.

In Java, we can create our own exceptions by extending the built-in Exception class.


To create a custom exception in Java, we need to create a new class that extends the Exception class or one of its subclasses, such as RuntimeException or IOException.

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

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

In this example, we have created a new class called MyException that extends the Exception class.

We have also defined a constructor that takes a string argument, which will be used as the error message for the exception.

Now, we can use this custom exception in our code by throwing it when necessary.

Here’s an example of how to throw a MyException in Java:

public void doSomething(int value) throws MyException {
   if (value < 0) {
      throw new MyException("Value cannot be negative");
   }
   // do something else
}

In this example, we have a method called doSomething that takes an integer argument.

If the value is less than zero, we throw a new instance of the MyException class with a message indicating that the value cannot be negative.

When we throw a custom exception in Java, we can catch it using a try-catch block just like any other exception.

Here’s an example of how to catch a MyException in Java:

public static void main(String[] args) {
   try {
      doSomething(-1);
   } catch (MyException e) {
      System.out.println("Caught exception: " + e.getMessage());
   }
}

In this example, we are calling the doSomething method with a negative value, which will cause a MyException to be thrown.

We catch the exception using a try-catch block and print out the error message using the getMessage method.


In conclusion, creating custom exceptions in Java is a simple process that involves extending the built-in Exception class or one of its subclasses and defining a constructor that takes a message argument.

We can then throw and catch our custom exceptions just like any other exception in Java.