Java program to create a custom exception class

Java example to create a custom exception class.
Submitted by Nidhi, on April 20, 2022

Problem Solution:

In this program, we will create a custom exception class by extending the Exception class. Then we will throw created exception in the try block, which is caught in the catch block, and print the exception message.

Program/Source Code:

The source code to create a custom exception class is given below. The given program is compiled and executed successfully.

// Java program to create a custom exception class

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

public class Main {
  public static void main(String[] args) {
    try {
      CustomException exp = new CustomException("Throw Custom Exception");

      throw exp;
    } catch (CustomException e) {
      System.out.println("Exception: " + e.getMessage());
    }
    System.out.println("Program finished");
  }
}

Output:

Exception: Throw Custom Exception
Program finished

Explanation:

In the above program, we created two classes CustomException, Main. The CustomException is created by extending the Exception class, it initializes the superclass constructor using the super keyword in its constructor.

The Main class contains the main() method. The main() method is the entry point for the program. And, created the object of CustomException class in the try block and thrown exception using the throw keyword, which is caught in the catch block, and printed the exception message.

Java Exception Handling Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.