Skip to main content

Chapter 1: Exception Handling

Introduction​

Exceptions are Java's mechanism for signaling errors. Using them well is essential for creating robust and maintainable applications.


🎯 Chapter Objectives​

By the end of this chapter, you will know how to:

  1. ✅ Differentiate Checked and Unchecked exceptions
  2. ✅ Create custom exceptions
  3. ✅ Organize an exception hierarchy
  4. ✅ Apply best practices

1. Reminder: Java Exception Hierarchy​

Throwable
├── Error (do not catch)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception
├── Checked Exceptions (must be declared)
│ ├── IOException
│ └── SQLException
└── RuntimeException (Unchecked)
├── NullPointerException
├── IllegalArgumentException
└── Your custom exceptions

2. Checked vs Unchecked​

Checked Exceptions​

// Must be declared with throws or caught
public void readFile(String path) throws IOException {
Files.readString(Path.of(path)); // IOException possible
}

// Or
public void readFile(String path) {
try {
Files.readString(Path.of(path));
} catch (IOException e) {
// Handle the error
}
}

When to use? Recoverable errors (missing file, network).

Unchecked Exceptions (RuntimeException)​

// No need to declare
public User findById(Long id) {
if (id == null) {
throw new IllegalArgumentException("ID cannot be null");
}
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}

When to use? Programming errors, contract violations.

In Spring Boot: Prefer Unchecked​

// ❌ Cumbersome to use
public User findById(Long id) throws UserNotFoundException {
// ...
}

// ✅ More fluid
public User findById(Long id) {
// Throws a RuntimeException if not found
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}

3. Creating Custom Exceptions​

Simple Exception​

public class UserNotFoundException extends RuntimeException {

public UserNotFoundException(Long id) {
super("User not found with ID: " + id);
}

public UserNotFoundException(String message) {
super(message);
}
}

Exception with Additional Data​

@Getter
public class ResourceNotFoundException extends RuntimeException {

private final String resourceType;
private final Object resourceId;

public ResourceNotFoundException(String resourceType, Object resourceId) {
super(String.format("%s not found with ID: %s", resourceType, resourceId));
this.resourceType = resourceType;
this.resourceId = resourceId;
}
}

// Usage
throw new ResourceNotFoundException("User", 123L);
throw new ResourceNotFoundException("Product", "SKU-001");

Exception with Error Code​

@Getter
public class BusinessException extends RuntimeException {

private final String errorCode;
private final Map<String, Object> details;

public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
this.details = new HashMap<>();
}

public BusinessException(String errorCode, String message, Map<String, Object> details) {
super(message);
this.errorCode = errorCode;
this.details = details;
}
}

// Usage
throw new BusinessException(
"INSUFFICIENT_BALANCE",
"Insufficient balance for withdrawal",
Map.of("requested", 500, "available", 100)
);

4. Business Exception Hierarchy​

// Base exception for the application
public abstract class ApplicationException extends RuntimeException {

private final String errorCode;

protected ApplicationException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}

protected ApplicationException(String errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}

public String getErrorCode() {
return errorCode;
}
}

Specific Exceptions​

// Resource not found (→ 404)
public class ResourceNotFoundException extends ApplicationException {

public ResourceNotFoundException(String resourceType, Object id) {
super("RESOURCE_NOT_FOUND",
String.format("%s with ID %s not found", resourceType, id));
}
}

// Validation failed (→ 400)
public class ValidationException extends ApplicationException {

private final List<FieldError> errors;

public ValidationException(List<FieldError> errors) {
super("VALIDATION_FAILED", "Validation failed");
this.errors = errors;
}
}

// Conflict (→ 409)
public class ConflictException extends ApplicationException {

public ConflictException(String message) {
super("CONFLICT", message);
}
}

// Unauthorized (→ 403)
public class ForbiddenException extends ApplicationException {

public ForbiddenException(String message) {
super("FORBIDDEN", message);
}
}

// Business error (→ 422)
public class BusinessRuleException extends ApplicationException {

public BusinessRuleException(String code, String message) {
super(code, message);
}
}

Diagram​

ApplicationException
├── ResourceNotFoundException → 404
├── ValidationException → 400
├── ConflictException → 409
├── ForbiddenException → 403
├── BusinessRuleException → 422
└── TechnicalException → 500

5. Usage Examples​

In a Service​

@Service
@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;

public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}

public User create(UserRequest request) {
// Check uniqueness
if (userRepository.existsByEmail(request.getEmail())) {
throw new ConflictException("Email already in use: " + request.getEmail());
}

// Create the user
User user = new User();
user.setEmail(request.getEmail());
user.setName(request.getName());
return userRepository.save(user);
}

public void delete(Long id) {
User user = findById(id); // Throws ResourceNotFoundException if not found

if (user.hasActiveOrders()) {
throw new BusinessRuleException(
"CANNOT_DELETE_USER_WITH_ORDERS",
"Cannot delete user with active orders"
);
}

userRepository.delete(user);
}
}

In a Controller (without centralized management)​

@RestController
@RequestMapping("/api/users")
public class UserController {

@GetMapping("/{id}")
public ResponseEntity<User> getById(@PathVariable Long id) {
try {
User user = userService.findById(id);
return ResponseEntity.ok(user);
} catch (ResourceNotFoundException e) {
return ResponseEntity.notFound().build();
}
}
}

Problem: Repetition of try-catch in each method!

Solution: @ControllerAdvice (next chapter)


6. Best Practices​

✅ Do​

// 1. Name clearly
public class InsufficientStockException extends BusinessRuleException { }
public class PaymentDeclinedException extends BusinessRuleException { }

// 2. Include context
throw new ResourceNotFoundException("Product", productId);

// 3. Use error codes
throw new BusinessRuleException("ORDER_LIMIT_EXCEEDED", "...");

// 4. Chain causes
try {
externalService.call();
} catch (ExternalServiceException e) {
throw new TechnicalException("External service failed", e);
}

❌ Avoid​

// 1. Generic exceptions
throw new Exception("Something went wrong"); // ❌

// 2. Empty messages
throw new RuntimeException(); // ❌

// 3. Catch and ignore
try {
riskyOperation();
} catch (Exception e) {
// Silent - ❌ NEVER!
}

// 4. Exceptions for normal flow
try {
user = findById(id);
} catch (UserNotFoundException e) {
user = createUser(id); // ❌ Use Optional instead
}

Pattern: Optional vs Exception​

// For "may not exist"
public Optional<User> findByEmail(String email) {
return userRepository.findByEmail(email);
}

// For "MUST exist"
public User getById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}

7. Native Spring Boot Exceptions​

ResponseStatusException​

@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND,
"User not found: " + id
));
}

Advantage: Simple, no need for @ControllerAdvice Disadvantage: Less flexible, no custom format

@ResponseStatus on Exception​

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super("User not found: " + id);
}
}

Advantage: Automatic Disadvantage: Default Spring response format


8. Summary​

Types of Exceptions​

TypeInheritanceUsage
CheckedExceptionRecoverable errors
UncheckedRuntimeExceptionBusiness errors, programming
ApplicationException (abstract)
├── ResourceNotFoundException (404)
├── ValidationException (400)
├── ConflictException (409)
├── BusinessRuleException (422)
└── TechnicalException (500)

Checklist​

✅ Exceptions inherit from RuntimeException
✅ Clear and informative messages
✅ Error codes for the API
✅ Context included (ID, resource type)
✅ Chained causes for debugging

🎯 Next Step​

You know how to create exceptions. Now, let's learn how to manage them globally with @ControllerAdvice.

➡️ Chapter 2: @ControllerAdvice


⬅️ Back to Module 10