Java Program to Create custom exception

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to create custom checked exception

Output

Swift is added to the ArrayList
[CustomException: Java already exists] Exception Occured

In the above example, we have extended the Exception class to create a custom exception named CustomException. Here, we call the constructor of Exception class from the CustomException class using super() keyword.

Inside the method checkLanguage(), we have checked the exception condition, and if the exception occurs, the try..catch block handles the exception.

Here, this is the checked exception. We can also create unchecked exception class in Java. To learn more on checked and unchecked exception, visit Java Exception.


Example 2: Create custom unchecked exception class

Output

Swift is added to the ArrayList
Exception in thread "main" CustomException: Java already exists
        at Main.checkLanguage(Main.java:21)
        at Main.main(Main.java:37)

In the above example, we have extended the RuntimeException class to create an unchecked custom exception class.

Here, you can notice that, we haven't declared any try...catch block. It is because the unchecked exception is checked at runtime.

Besides that, other functionality of unchecked exception is similar to the above mentioned program.