Java Custom Exception - User Defined Exceptions With Examples

Custom Exceptions or User-Defined Exceptions are very common in Java applications. We can easily create custom exception classes for different use cases.

What are the different types of Exceptions?

In Java, there are two categories of Exceptions:

  • Checked Exceptions – These are recoverable. These are derived from the Exception class. For example, IOException and FileNotFoundException are checked exceptions.
  • Unchecked Exceptions – These are not recoverable and occur at runtime. These are derived from java.lang.RuntimeException class. For example, NullPointerException and IllegalArgumentException are unchecked exceptions.

Further Reading: Exception Handling in Java.

Moving ahead, let’s look at custom exceptions in the next section.

Java Custom Exceptions or User-Defined Exceptions

Custom Exceptions are user-defined exceptions. These are written by programmers specifically for there application use cases.

To create a checked custom exception, it must extend Exception or its child classes.Unchecked custom exception extends RuntimeException or its child classes.

All Exceptions are a child of Throwable.

Before we get down to the implementation part, let’s make note of a few points.

  • Create Custom Exceptions only when they provide a specific use case that none of the available Exceptions provide.
  • All custom exceptions must follow the standard naming convention. That is camel case and ending with the word “Exception”.
  • Use overloaded constructors for all scenarios.

1. Custom Unchecked Exceptions

An example of custom unchecked exceptions is given below.


Java Custom Unchecked Exception

In the above program, we simply throw an error when the value is not present in the ArrayList.

In the custom exception, we have defined multiple constructors to cover different cases.

The getMessage() and getLocalisedMessage() are overridden to provide custom responses.

2. User-Defined Checked Exception

Here is a simple example of user-defined checked exception. We will extend the Exception class and override the toString() method.


Summing up, Custom Exceptions behave like built-in Exception types. Create a custom exception whenever you need to handle your application/module specific exceptions and boundaries.

By admin

Leave a Reply