User Not Found Exception
In this lesson, we'll implement an exception that is thrown when a user is not found in our system.
This will help us handle error cases in a clean and organized way.
Understanding Custom Exceptions
Custom exceptions help us handle application-specific error cases in a way that makes sense for our domain.
When creating custom exceptions, it's helpful to have a base exception class that all other exceptions extend.
Let's create our base exception class:
public class EventTicketException extends RuntimeException {
public EventTicketException() {
}
public EventTicketException(String message) {
super(message);
}
public EventTicketException(String message, Throwable cause) {
super(message, cause);
}
public EventTicketException(Throwable cause) {
super(cause);
}
public EventTicketException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}Creating the User Not Found Exception
Now that we have our base exception, we can create our specific exception for when a user is not found:
public class UserNotFoundException extends EventTicketException {
public UserNotFoundException() {
}
public UserNotFoundException(String message) {
super(message);
}
public UserNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public UserNotFoundException(Throwable cause) {
super(cause);
}
public UserNotFoundException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}Using Runtime Exceptions
We extend RuntimeException in our base exception class rather than Exception.
This choice means we don't need to declare throws clauses on methods that might throw our exceptions.
This approach, recommended by Robert C. Martin in "Clean Code", helps maintain the Open-Closed Principle by preventing changes to method signatures when new exceptions are added.
Summary
- Created a
EventTicketExceptionparent custom exception - Created the
UserNotFoundExceptionto represent the invalid state when a specified user does not exist