Creating custom exceptions in Java

Upasana | August 05, 2019 | 1 min read | 854 views


If we need a fine-grained categorization of error/exceptional situations, Java provides us with an option to define custom exceptions with detailed message that differentiate one situation from another.

New custom exceptions are usually defined by either extending Exception class or its subclass (checked exception), or by extending the RuntimeException (unchecked exception).

Custom exceptions, just like any normal class can declare fields and methods, thereby providing more information as to their cause.

Creating a custom checked exception

Lets create a custom checked exception which will be thrown whenever a database record conflict occurs.

We can add additional details to ths exception for example, date and errorCode which can provide granular details about the exception situation.

Custom checked exception
public class DBConflictException extends Exception {
    Date date;
    int errorCode;

    public DBConflictException(Date date, int errorCode) {
        super("DB record Conflict Exception " + errorCode); (1)
        this.date = date;
        this.errorCode = errorCode;
    }

}
1 Calling the constructor or the superclass.

Custom unchecked exception

In a very similar fashion we can create custom unchecked exception by extending from RuntimeException class. If you are using Spring, we often need to create custom exception from RestControllers, one such example is shown below:

Custom unchecked exception
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Could not find this resource on server")
public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String reason) {
       super(reason);
    }
}

That’s all for now.


Top articles in this category:
  1. 50 Java Interview Questions for SDET Automation Engineer
  2. Java Coding Problems for SDET Automation Engineer
  3. Junit interview questions for SDET automation engineer
  4. Rest Assured API Testing Interview Questions
  5. Creating custom Tag in Junit5 based tests
  6. Essential Java Skills for SDET Automation Engineer
  7. Java 11 HttpClient with Basic Authentication

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.