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
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.
Output: