WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Boot & Hibernate · Intermediate · question 32 of 100

How do you create and handle custom exceptions in a Spring Boot application?

📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

In a Spring Boot application, custom exceptions can be created and handled using Java’s standard exception handling mechanisms, along with Spring’s exception handling features.

To create a custom exception, you can create a new class that extends Exception or one of its subclasses, such as RuntimeException. Here is an example of a custom exception:

    public class UserNotFoundException extends RuntimeException {
        public UserNotFoundException(String message) {
            super(message);
        }
    }

In this example, we have created a custom exception called UserNotFoundException, which extends RuntimeException. This exception can be thrown when a user is not found in the database.

To handle the custom exception, we can create an exception handler method in a @ControllerAdvice class. Here is an example:

    @ControllerAdvice
    public class ExceptionHandlerAdvice {
        @ExceptionHandler(UserNotFoundException.class)
        public ResponseEntity<String> handleUserNotFoundException(UserNotFoundException ex) {
            return ResponseEntity.status(HttpStatus.NOT\_FOUND).body(ex.getMessage());
        }
    }

In this example, we have created an exception handler method called handleUserNotFoundException that handles UserNotFoundException. The method returns a ResponseEntity object with a status code of 404 NOT_FOUND and the exception message as the response body.

To throw the custom exception, we can simply create a new instance of the exception and throw it in the appropriate place in our code. Here is an example:

    @Service
    public class UserService {
        @Autowired
        private UserRepository userRepository;
        
        public User getUserById(Long id) {
            Optional<User> user = userRepository.findById(id);
            if (user.isPresent()) {
                return user.get();
            } else {
                throw new UserNotFoundException("User not found with ID: " + id);
            }
        }
    }

In this example, we have a UserService class that retrieves a user by ID from a UserRepository. If the user is not found, we throw a UserNotFoundException with an appropriate error message.

Overall, creating and handling custom exceptions in a Spring Boot application is a powerful and flexible way to handle error conditions in your code. By creating custom exceptions and handling them with @ControllerAdvice and @ExceptionHandler, developers can provide meaningful error messages to users and gracefully handle exceptions in their code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Boot & Hibernate interview — then scores it.
📞 Practice Spring Boot & Hibernate — free 15 min
📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

All 100 Spring Boot & Hibernate questions · All topics