Creating custom exceptions in Java

Carvia Tech | August 05, 2019 | 1 min read | 755 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) = 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) {

That’s all for now.

Top articles in this category:
  1. 50 SDET Java Interview Questions & Answers
  2. SDET Java Coding Challenges
  3. Rest Assured API Testing Interview Questions
  4. SDET: JUnit interview questions for automation engineer
  5. Creating custom Tag in Junit5 based tests
  6. Java 11 HttpClient with Basic Authentication
  7. Factorial in Java using recursion

Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info