Java Custom Exception

Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java throw keyword is used to throw the Java Custom Exception. One can throw a checked as well as an unchecked custom exception.

Throwing a Custom Checked Exception

For creating a custom-checked exception, the Java Exception class must be extended. The custom-checked exception is detected at the compile time. The following program illustrates how one can raise a custom-checked exception.

FileName: CustomCheckException.java

Output:

Explanation:The above program is written in such a way that it only raises the custom exception when anything other than a small letter is passed.The second string of the array names contains a capital letter ‘S’, and because of it, the custom exception is raised for the second string “Sumit”.

Throwing a Custom Un-Checked Exception

Un-checked exceptions are those exceptions that are checked at the runtime. To throw an un-checked exception, the class RuntimeException must be extended. Let’s observe the following program for a better understanding.

FileName: CustomCheckException1.java

Output:

Explanation: The above program throws the exceptions when it encounters a number greater than 20.

Pin It on Pinterest

Share This