Creating custom exceptions in Java

Carvia Tech | August 05, 2019 | 1 min read | 28 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. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: JUnit interview questions for automation engineer
  3. Commonly used Http methods in RESTful services
  4. Create anagram buckets from a given input array of words
  5. Write a program to reverse a string using recursion in Java
  6. Write a program to reverse the order of words in a string
  7. Check if the given number is Armstrong Number in Java



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