JAVA

What is Custom Exception in JAVA ?

What is Custom Exception in JAVA ?

In Java, there are two types of exceptions – checked and unchecked exception. Here’s the summary :

Checked – Extends java.lang.Exception, for recoverable condition, try-catch the exception explicitly, compile error.
Unchecked – Extends java.lang.RuntimeException, for unrecoverable condition, like programming errors, no need try-catch, runtime error.

Custom Checked Exception

Some popular checked exception : IOException, FileNotFoundException
1.1 If the client is able to recover from the exception, make it a checked exception. To create a custom checked exception, extends java.lang.Exception

Also Read : How to change date format in a String in JAVA

If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let’s see a simple example of java custom exception.

NameNotFoundException.java

1.2 For checked exception, you need to try and catch the exception.

CustomerService.java

Output

Custom Unchecked Exception

Some popular unchecked exception : NullPointerException, IndexOutOfBoundsException, IllegalArgumentException
2.1 If the client cannot do anything to recover from the exception, make it an unchecked exception. To create a custom unchecked exception, extends java.lang.RuntimeException

ListTooLargeException.java

2.3 For unchecked exception, try and catch the exception is optional.

CustomerService.java

Output

 

Custom exceptions are very much useful when we need to handle specific exceptions related to the business logic. When used properly, they can serve as a useful tool for better exception handling and logging.