Q:

Java program to create a custom exception class

belongs to collection: Java Exception Handling Programs

0

Java program to create a custom exception class

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Java program to get exception message using getMes...