Custom Exception In Java

By | | Updated : 2022-03-18 | Viewed : 142 times

User Defined Exception In Java

In many of the applications, the users/developer needs a more comprehensible error message. In java, it can be achieved by the Custom/User-Defined Exceptions.

Exception In Java

An Exception is an event and is also called a run time error that occurred in run time. Generally, exception interrupts the normal flow of the application/program's execution. once an exception occurred in an application/program, then execution flow is stopped abnormally.

Custom Exception In Java

Java provides us a nice facility to create Custom exceptions. Custom exceptions are especially for creating new exceptions with a meaningful error message for users/developers who are using our API/program. So it will be easy to under the cause of the error that occurred in runtime.

Custom exceptions are created like as normal exceptions that we create with the throw keyword. But here we will supply a need error message to that exception.

Why Use Custom Exception In Java

Primarily, custom exceptions are created and used for these two reasons.

  • API Developers can catch that particular custom exception and add the required business logic code into that catch block if anything is required.

  • Users can easily understand the runtime error in the application/Program.

Implement Custom Exception

Custom Exception in Java can be created as a normal class but it should be extended with class RuntimeException/Exception with keyword extends.

And Custom Exception should contain one constructor. Here it is required to call RuntimeException/Exception's constructor.

Note: We can create the custom exception without constructor as well but it is not a recommended approach as we can not pass the required error message.

Custom Exception Example in Java

Notice below given example how we implemented as per mentioned instructions above.

EmployeeNotFoundException.java
public class EmployeeNotFoundException extends Exception {

    public EmployeeNotFoundException(String s)
    {
        super(s);
    }

}
ExceptionUtils.java
public class ExceptionUtils {
    public Employee getEmployee(Integer id) throws EmployeeNotFoundException {
        if(id != null){
            return new Employee();
        }
        throw new EmployeeNotFoundException("Employee is not existed with given id.");

    }
   //
}
ExceptionUtilsTest.java
@Test
    public void getEmployeeTest() throws Exception {

        Exception exception = assertThrows(EmployeeNotFoundException.class, () -> {
            new ExceptionUtils().getEmployee(null);
        });
        String expectedMessage = "Employee is not existed with given id.";
        String actualMessage = exception.getMessage();
        assertTrue(actualMessage.contains(expectedMessage));
    }

Please refer GitHub repo Java-Custom-Exception-Example-App

Leave A Reply