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) {

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");


Exception: Throw Custom Exception
Program finished


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!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.