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
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.
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:
- 50 Java Interview Questions for SDET Automation Engineer
- Java Coding Problems for SDET Automation Engineer
- Junit interview questions for SDET automation engineer
- Rest Assured API Testing Interview Questions
- Creating custom Tag in Junit5 based tests
- Essential Java Skills for SDET Automation Engineer
- Java 11 HttpClient with Basic Authentication