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;
}
}
Creating custom exceptions in Java
Carvia Tech | 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.
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:
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:
- SDET: JUnit interview questions for automation engineer
- 50 SDET Java Interview Questions & Answers
- Rest Assured API Testing Interview Questions
- Creating custom Tag in Junit5 based tests
- SDET Java Coding Challenges
- Java 11 HttpClient with Basic Authentication
- Difference between Enumeration and Iterator in Java
Find more on this topic:
Subscribe to Interview Questions
Recommended books for interview preparation:
Similar Posts
- Reverse position of words in a string using recursion
- REST Assured with plain/text response body
- Get distinct words from a given file in Java
- SDET Java Coding Challenges
- REST Assured vs Apache HttpClient and RestTemplate
- Java 11 HttpClient with Basic Authentication
- HTTP GET request with Java 11 HttpClient - Kotlin
- HTTP Head request using Java 11 HttpClient - Kotlin
- Using Java 11 HttpClient with Kotlin Coroutines
- Migrating Spring Boot tests from Junit 4 to Junit 5