Exception Handling
Alan Biju
@itsmeambro
Exception Handling
1. Exception Handling in Java
Exception handling is a critical concept in Java and Spring Boot
applications to ensure robust and maintainable code.
Types of Exceptions
(i) Checked Exceptions (Compile-time):
Must be handled using try-catch or throws.
Examples: IOException, SQLException, FileNotFoundException
(ii) Unchecked Exceptions (Runtime)
Do not require explicit handling.
Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException
(iii) Errors
Indicate serious problems (not recoverable).
Examples: OutOfMemoryError, StackOverflowError
Java Exception Handling Best Practices
✅ Use Meaningful Custom Exceptions
public void loginUser(String username) {
if (username == null || username.isEmpty()) {
throw new InvalidUserException("Username cannot be empty");
}
}
✅ Never Swallow Exceptions: log exceptions properly
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.err.println("Error: Division by zero");
}
✅ Use try-with-resources for Resource Management
Java 7+ introduced try-with-resources to auto-close resources like
BufferedReader, FileWriter, Connection, etc.
try (BufferedReader br = new BufferedReader(
new FileReader("data.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
Alan Biju
01 @itsmeambro
System.err.println("Error reading file: " +
e.getMessage());
}
Prevents memory leaks
Automatically closes resources
✅ Use finally Block Wisely
finally is used for cleanup (closing DB connections, files, etc.).
Connection conn = null;
try {
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/db",
"user", "password");
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.err.println("Error closing connection");
}
}
}
✅ Use throw vs throws Correctly
throws → Declares an exception in method signature.
throw → Used to actually throw an exception.
void process() throws IOException {
throw new IOException("File not found");
}
Alan Biju
02 @itsmeambro
2. Exception Handling in Spring Boot
Spring Boot provides a centralized way to handle exceptions using
the @ExceptionHandler, @ControllerAdvice, and
ResponseEntityExceptionHandler.
1️⃣ Using @ExceptionHandler (Local Handling)
You can use @ExceptionHandler in a controller to handle specific
exceptions.
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable int id) {
if (id <= 0) {
throw new UserNotFoundException("User not found with
ID: " + id);
}
return new User(id, "John Doe");
}
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String>
handleUserNotFoundException(UserNotFoundException ex) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
}
2️⃣ Using @ControllerAdvice (Global Exception Handling)
Instead of handling exceptions inside individual controllers, we can create
a global handler.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String>
handleUserNotFoundException(UserNotFoundException ex) {
Alan Biju
03 @itsmeambro
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception
ex) {
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred: " + ex.getMessage());
}
}
3️⃣ Using ResponseEntityExceptionHandler for Standard Responses
Extending ResponseEntityExceptionHandler provides more control.
@RestControllerAdvice
public class CustomExceptionHandler extends
ResponseEntityExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
protected ResponseEntity<Object> handleUserNotFoundException(
UserNotFoundException ex,
WebRequest request) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", new Date());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
}
}
Alan Biju
04 @itsmeambro
📌 Exception Handling Best Practices
✅ Use specific exceptions instead of Exception
✅ Provide meaningful messages for debugging
✅ Never swallow exceptions (log or handle them)
✅ Use finally or try-with-resources for cleanup
✅ Avoid logging + throwing the same exception
✅ Use @ControllerAdvice for centralized exception handling.
✅ Use meaningful HTTP status codes (404 NOT FOUND, 400 BAD
REQUEST).
✅ Avoid exposing sensitive details in error messages.
✅ Use custom exceptions for clarity (UserNotFoundException,
InvalidRequestException).
✅ Log exceptions properly (logger.error("Error Message", ex)).
Alan Biju
05 @itsmeambro
If you find this
helpful, like and
share it with your
friends
Alan Biju
@itsmeambro