Custom exception in java and its use

Here we will see how to create custom exception in java and what is the use of them.

When we create own exception by extending Exception class or RuntimeException class, it is called a custom exception.

The custom exception is mainly used to show custom messages.

Steps to define custom exception –

  1. Define CustomException class(generally it should be your application name) extending Exception or  RuntimeException class.
  2. Define one and two parametrized constructor.
  3. In each constructor, we need to define super.
  4. Use throw keyword to show the proper exception message.

Creating a custom exception extending Exception class.

Output is –

customexception.CustomException: book id can’t be null
at customexception.CustomException.main(CustomException.java:20)

 

Creating a custom exception extending RuntimeException class.

 

Output is –

Exception in thread “main” customexception.CustomException1: problem in parsing the date
at customexception.CustomException1.main(CustomException1.java:27)

 

We can make the exception message more understandable, using two parametrized constructor.

 

 

Example –

Output is –

Exception in thread “main” customexception.CustomException1: problem in parsing the date
at customexception.CustomException1.main(CustomException1.java:27)
Caused by: java.text.ParseException: Unparseable date: “11101988”
at java.text.DateFormat.parse(Unknown Source)
at customexception.CustomException1.main(CustomException1.java:25)

Obserb the output of both example. We have more specific message now.

 

So now the question arises what is the difference between extending Exception class and RuntimeException. While extending Exception class it will create checked exception whereas If we extends RuntimeException it will be created an Unchecked exception.

 

 

Top