📖 Scenario: You are building a simple Spring Boot application that manages user accounts. You want to handle errors clearly by creating your own exception class for when a user is not found.
🎯 Goal: Create a custom exception class called UserNotFoundException that extends RuntimeException. Then configure a controller advice to handle this exception and return a friendly error message.
📋 What You'll Learn
Create a custom exception class named UserNotFoundException that extends RuntimeException
Add a constructor to UserNotFoundException that accepts a String message and passes it to the superclass
Create a Spring @RestControllerAdvice class named GlobalExceptionHandler
Add a method in GlobalExceptionHandler annotated with @ExceptionHandler(UserNotFoundException.class) that returns a ResponseEntity<String> with the exception message and HTTP status NOT_FOUND
💡 Why This Matters
🌍 Real World
Custom exceptions help make error handling clear and consistent in real applications, improving user experience and debugging.
💼 Career
Understanding how to create and handle custom exceptions is essential for backend developers working with Spring Boot to build robust APIs.
Progress0 / 4 steps
1
Create the custom exception class
Create a public class called UserNotFoundException that extends RuntimeException. Add a constructor that accepts a String message and passes it to super(message).
Spring Boot
Hint
Remember to extend RuntimeException and create a constructor that calls super(message).
2
Create the global exception handler class
Create a public class called GlobalExceptionHandler annotated with @RestControllerAdvice. This class will handle exceptions globally.
Spring Boot
Hint
Use @RestControllerAdvice annotation on the class GlobalExceptionHandler.
3
Add exception handler method
Inside GlobalExceptionHandler, add a method annotated with @ExceptionHandler(UserNotFoundException.class). The method should return ResponseEntity<String> with the exception message and HTTP status NOT_FOUND. Use method signature: public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex).
Spring Boot
Hint
Use @ExceptionHandler(UserNotFoundException.class) and return a ResponseEntity with the exception message and HttpStatus.NOT_FOUND.
4
Complete imports and class structure
Add all necessary import statements for ResponseEntity, HttpStatus, ExceptionHandler, and RestControllerAdvice at the top of the file to complete the code.
Spring Boot
Hint
Make sure all required Spring annotations and classes are imported.
Practice
(1/5)
1. What is the main purpose of creating a custom exception class in Spring Boot?
easy
A. To automatically fix errors without any code changes
B. To replace all built-in exceptions with your own versions
C. To make the application run faster by skipping error checks
D. To handle specific error cases clearly and separately in your application
Solution
Step 1: Understand the role of custom exceptions
Custom exceptions help you identify and manage specific error situations clearly in your code.
Step 2: Compare with other options
Replacing all exceptions or auto-fixing errors is not the goal; custom exceptions improve clarity and control.
Final Answer:
To handle specific error cases clearly and separately in your application -> Option D
Quick Check:
Custom exceptions clarify error handling = C [OK]
Hint: Custom exceptions clarify specific errors clearly [OK]
Common Mistakes:
Thinking custom exceptions replace all errors
Believing they fix errors automatically
Assuming they improve performance directly
2. Which of the following is the correct way to declare a custom exception class in Spring Boot?
easy
A. public class MyException extends RuntimeException { public MyException(String message) { super(message); } }
B. public interface MyException extends RuntimeException {}
C. public class MyException implements RuntimeException {}
D. public class MyException extends Exception {}
Solution
Step 1: Check correct inheritance
Custom exceptions usually extend RuntimeException to avoid mandatory try-catch blocks.
Step 2: Verify constructor usage
Providing a constructor that calls super(message) is standard to pass error messages.
Final Answer:
public class MyException extends RuntimeException { public MyException(String message) { super(message); } } -> Option A
Quick Check:
Extend RuntimeException with constructor = D [OK]
Hint: Extend RuntimeException and add constructor with message [OK]
Common Mistakes:
Using implements instead of extends
Extending Exception instead of RuntimeException
Declaring interface instead of class
3. Given this custom exception class:
public class DataNotFoundException extends RuntimeException {
public DataNotFoundException(String message) {
super(message);
}
}
What will happen if this exception is thrown in a Spring Boot controller without any handler?
medium
A. The exception will be ignored and the request will succeed
B. The application will return a 500 Internal Server Error response
C. The application will automatically return a 404 Not Found response
D. The server will crash and stop running
Solution
Step 1: Understand default Spring Boot behavior
Without a handler, Spring Boot treats RuntimeExceptions as server errors and returns HTTP 500.
Step 2: Check other options
Ignoring exceptions or auto 404 responses require explicit handling; server crash does not happen.
Final Answer:
The application will return a 500 Internal Server Error response -> Option B
Quick Check:
Unhandled RuntimeException = HTTP 500 error [OK]
Hint: Unhandled RuntimeException returns HTTP 500 by default [OK]
Common Mistakes:
Assuming automatic 404 response
Thinking exceptions are ignored
Believing server crashes on exception
4. Identify the error in this custom exception class:
public class InvalidInputException extends RuntimeException {
public InvalidInputException() {
super();
}
public void InvalidInputException(String message) {
super(message);
}
}
medium
A. The class should extend Exception, not RuntimeException
B. The first constructor should accept a message parameter
C. The second method should be a constructor but is declared as void
D. There is no error; the class is correct
Solution
Step 1: Check method declarations
The second method has a return type void, so it is not a constructor but a normal method.
Step 2: Understand constructor syntax
Constructors must not have a return type; this causes the message constructor to be invalid.
Final Answer:
The second method should be a constructor but is declared as void -> Option C
Quick Check:
Constructor must not have return type = B [OK]
Hint: Constructors have no return type, not even void [OK]
Common Mistakes:
Adding void to constructor
Confusing methods with constructors
Extending wrong exception class
5. How can you handle a custom exception ResourceMissingException globally in Spring Boot to return a 404 status with a custom message?
hard
A. Create a @ControllerAdvice class with a method annotated @ExceptionHandler(ResourceMissingException.class) that returns ResponseEntity with status 404 and message
B. Throw ResourceMissingException inside a try-catch block and catch it in every controller method separately
C. Override the default error page in Spring Boot without using @ExceptionHandler
D. Use @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) on the exception class
Solution
Step 1: Use @ControllerAdvice for global handling
This annotation allows centralized exception handling across all controllers.
Step 2: Define @ExceptionHandler method for ResourceMissingException
This method can build a ResponseEntity with HTTP 404 and a custom message to send back.
Final Answer:
Create a @ControllerAdvice class with a method annotated @ExceptionHandler(ResourceMissingException.class) that returns ResponseEntity with status 404 and message -> Option A
Quick Check:
Global handler with @ExceptionHandler = A [OK]
Hint: Use @ControllerAdvice and @ExceptionHandler for global exception handling [OK]
Common Mistakes:
Catching exceptions in every controller method
Using wrong HTTP status annotation
Overriding error page without exception handler
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.