Skip to content

jabrena/plinth / skills/126-java-exception-handling

126-java-exception-handling

Verified

Use when you need to apply Java exception handling best practices — including using specific exception types, managing resources with try-with-resources, securing exception messages, preserving error context via exception chaining, validating inputs early with fail-fast principles, handling thread interruption correctly, documenting exceptions with @throws, enforcing logging policy, translating exceptions at API boundaries, managing retries and idempotency, enforcing timeouts, attaching suppressed exceptions, and propagating failures in async/reactive code. This should trigger for requests such as Exception handling; Use try-with-resources in Java code; Create exception chaining in Java code; Apply fail-fast validation in Java code; Review Java exception taxonomy and propagation. Part of Plinth Toolkit

FileKindSize
SKILL.mdskill md3.7 KB
references/126-java-exception-handling.mdmarkdown94.5 KB

references/126-java-exception-handling.md

View on GitHub
---
name: 126-java-exception-handling
description: Use when you need to apply Java exception handling best practices — including using specific exception types, managing resources with try-with-resources, securing exception messages, preserving error context via exception chaining, validating inputs early with fail-fast principles, handling thread interruption correctly, documenting exceptions with @throws, enforcing logging policy, translating exceptions at API boundaries, managing retries and idempotency, enforcing timeouts, attaching suppressed exceptions, and propagating failures in async/reactive code.
license: Apache-2.0
metadata:
  author: Juan Antonio Breña Moral
  version: 0.19.0
---
# Java Exception Handling Guidelines

## Role

You are a Senior software engineer with extensive experience in Java software development

## Goal

This document provides comprehensive guidelines for robust Java exception handling practices. It covers fundamental principles including using specific exception types for different error scenarios, implementing proper resource management with try-with-resources, secure exception handling that prevents information leakage, proper exception chaining to preserve context, input validation with appropriate exceptions, thread interruption handling, and comprehensive exception documentation. The guidelines emphasize creating maintainable, secure, and debuggable error handling code that provides clear diagnostic information while protecting sensitive system details.

### Implementing These Principles

These guidelines are built upon the following core principles:

1. **Specific Exception Types**: Use specific exception types rather than generic `Exception` or `RuntimeException`. Create custom exceptions when needed to provide clear semantic meaning about what went wrong.
2. **Resource Management**: Always use try-with-resources for automatic resource cleanup. Ensure resources are properly closed even in exception scenarios.
3. **Input Validation**: Validate input parameters early and throw appropriate exceptions (`IllegalArgumentException`, `NullPointerException`) with descriptive messages.
4. **Secure Exception Handling**: Never expose sensitive information in exception messages. Log detailed information for developers while providing generic messages to users.
5. **Exception Chaining**: Preserve original exception context by using exception chaining to maintain the full error context for debugging.
6. **Thread Safety**: Handle `InterruptedException` properly by restoring the interrupted status and taking appropriate action.
7. **Documentation**: Document all checked exceptions with `@throws` tags and provide clear descriptions of when and why exceptions are thrown.
8. **Fail-Fast Principle**: Detect and report errors as early as possible rather than allowing invalid state to propagate through the system.
9. **Logging Policy**: Use structured logging with correlation IDs and error codes. Avoid log-and-throw duplication; log once at the boundary that decides the response.
10. **API Boundary Translation**: Translate lower-level exceptions into domain or transport-specific errors at application boundaries (e.g., controllers, message handlers) using centralized mappers/handlers.
11. **Retry and Idempotency**: Retry only idempotent operations with bounded attempts and backoff. Never retry on non-idempotent operations unless protected by idempotency keys.
12. **Timeouts and Deadlines**: Enforce timeouts and propagate deadline-exceeded errors. Cancel ongoing work on timeout and restore the interrupted status when applicable.
13. **Suppressed Exceptions**: When rethrowing after cleanup failures, attach secondary errors via `Throwable#addSuppressed` to preserve diagnostics.
14. **Do Not Catch Throwable/Error**: Catch specific exceptions. Do not catch `Throwable` or `Error` types; let fatal JVM errors propagate.
15. **Observability**: Emit metrics for error classes and latency; include correlation/request IDs in logs. Ensure error categorization supports SLO/SLA monitoring.
16. **Asynchronous/Reactive Propagation**: In async code (`CompletionStage`, callbacks), propagate failures without blocking; honor cancellation and interruption semantics.

## Constraints

Before applying any recommendations, ensure the project is in a valid state by running Maven compilation. Compilation failure is a BLOCKING condition that prevents any further processing.

- **MANDATORY**: Run `./mvnw compile` or `mvn compile` before applying any change
- **PREREQUISITE**: Project must compile successfully and pass basic validation checks before any optimization
- **CRITICAL SAFETY**: If compilation fails, IMMEDIATELY STOP and DO NOT CONTINUE with any recommendations
- **BLOCKING CONDITION**: Compilation errors must be resolved by the user before proceeding with any exception handling improvements
- **NO EXCEPTIONS**: Under no circumstances should design recommendations be applied to a project that fails to compile

## Examples

### Table of contents

- Example 1: Input Validation with Specific Exceptions
- Example 2: Resource Management with Try-With-Resources
- Example 3: Secure Exception Handling
- Example 4: Exception Chaining and Context Preservation
- Example 5: Thread Interruption and Concurrent Exception Handling
- Example 6: Custom Exception Design and Documentation
- Example 7: Use Exceptions Only for Exceptional Conditions
- Example 8: Use Checked Exceptions for Recoverable Conditions and Runtime Exceptions for Programming Errors
- Example 9: Favor the Use of Standard Exceptions
- Example 10: Include Failure-Capture Information in Detail Messages
- Example 11: Don't Ignore Exceptions
- Example 12: Testing Exception Scenarios Effectively
- Example 13: Logging Policy: Structured, De-duplicated Logging
- Example 14: Exception Translation at API Boundaries
- Example 15: Retry with Backoff Only for Idempotent Operations
- Example 16: Timeouts, Deadlines and Cancellation
- Example 17: Preserve Secondary Failures with Suppressed Exceptions
- Example 18: Do Not Catch Throwable or Error
- Example 19: Exception Handling in Lambda Expressions and Streams
- Example 20: Exception Handling in Constructors

### Example 1: Input Validation with Specific Exceptions

Title: Validate Early and Fail Fast with Descriptive Exceptions
Description: Validate input parameters at method entry points and throw specific, descriptive exceptions immediately when validation fails. This prevents invalid data from propagating through the system and makes debugging easier.

**Good example:**

```java
// GOOD: Specific input validation with descriptive exceptions
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class UserService {

    /**
     * Creates a new user with validated input.
     *
     * @param username the username, must not be null or empty
     * @param email the email address, must be valid format
     * @param age the user's age, must be between 13 and 120
     * @return the created user
     * @throws IllegalArgumentException if any parameter is invalid
     * @throws NullPointerException if username or email is null
     */
    public User createUser(String username, String email, int age) {
        // Null checks first
        Objects.requireNonNull(username, "Username cannot be null");
        Objects.requireNonNull(email, "Email cannot be null");

        // Specific validation with descriptive messages
        if (username.trim().isEmpty()) {
            throw new IllegalArgumentException("Username cannot be empty or whitespace only");
        }

        if (username.length() < 3 || username.length() > 50) {
            throw new IllegalArgumentException("Username must be between 3 and 50 characters, was: " + username.length());
        }

        if (!isValidEmail(email)) {
            throw new IllegalArgumentException("Invalid email format: " + email);
        }

        if (age < 13 || age > 120) {
            throw new IllegalArgumentException("Age must be between 13 and 120, was: " + age);
        }

        return new User(username.trim(), email.toLowerCase(), age);
    }

    /**
     * Processes a list of items, validates the list is not empty.
     *
     * @param items the list to process, must not be null or empty
     * @return processed results
     * @throws IllegalArgumentException if list is null or empty
     */
    public <T> List<T> processItems(List<T> items) {
        if (items == null) {
            throw new IllegalArgumentException("Items list cannot be null");
        }

        if (items.isEmpty()) {
            throw new IllegalArgumentException("Items list cannot be empty");
        }

        // Process items...
        return items.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    private boolean isValidEmail(String email) {
        return email.contains("@") && email.contains(".");
    }
}
```

**Bad example:**

```java
// AVOID: Poor input validation and generic exceptions
public class BadUserService {

    // BAD: No validation, allows invalid state
    public User createUser(String username, String email, int age) {
        return new User(username, email, age); // Could create invalid user
    }

    // BAD: Generic exception without descriptive message
    public User createUserBad(String username, String email, int age) throws Exception {
        if (username == null || email == null) {
            throw new Exception("Invalid input"); // Too generic
        }
        return new User(username, email, age);
    }

    // BAD: Catching validation errors too late
    public User createUserWorse(String username, String email, int age) {
        try {
            // Process without validation
            User user = new User(username, email, age);
            user.save(); // Might fail with cryptic database error
            return user;
        } catch (Exception e) {
            throw new RuntimeException("Failed to create user", e); // Lost context
        }
    }

    // BAD: No parameter validation
    public <T> List<T> processItems(List<T> items) {
        return items.stream() // NullPointerException if items is null
            .collect(Collectors.toList());
    }
}
```

### Example 2: Resource Management with Try-With-Resources

Title: Ensure Proper Resource Cleanup in All Scenarios
Description: Use try-with-resources for automatic resource management. This ensures resources are properly closed even when exceptions occur, preventing resource leaks and improving application reliability.

**Good example:**

```java
// GOOD: Proper resource management with try-with-resources
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResourceManager {
    private static final Logger logger = LoggerFactory.getLogger(ResourceManager.class);

    /**
     * Reads file content safely with automatic resource cleanup.
     *
     * @param filePath the path to read from
     * @return file content as string
     * @throws FileProcessingException if file cannot be read
     */
    public String readFileContent(Path filePath) throws FileProcessingException {
        Objects.requireNonNull(filePath, "File path cannot be null");

        try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) {
            return reader.lines()
                .collect(Collectors.joining(System.lineSeparator()));

        } catch (NoSuchFileException e) {
            logger.warn("File not found: {}", filePath);
            throw new FileProcessingException("File not found: " + filePath.getFileName(), e);

        } catch (AccessDeniedException e) {
            logger.error("Access denied reading file: {}", filePath);
            throw new FileProcessingException("Access denied to file", e);

        } catch (IOException e) {
            logger.error("IO error reading file: {}", filePath, e);
            throw new FileProcessingException("Failed to read file", e);
        }
    }

    /**
     * Executes database query with proper resource management.
     *
     * @param query the SQL query to execute
     * @param parameters query parameters
     * @return query results
     * @throws DatabaseException if query execution fails
     */
    public List<Map<String, Object>> executeQuery(String query, Object... parameters)
            throws DatabaseException {
        Objects.requireNonNull(query, "Query cannot be null");

        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(query)) {

            // Set parameters safely
            for (int i = 0; i < parameters.length; i++) {
                statement.setObject(i + 1, parameters[i]);
            }

            try (ResultSet resultSet = statement.executeQuery()) {
                return extractResults(resultSet);
            }

        } catch (SQLException e) {
            logger.error("Database query failed: {}", query, e);
            throw new DatabaseException("Query execution failed", e);
        }
    }

    /**
     * Writes properties to file with proper resource management.
     *
     * @param properties the properties to write
     * @param filePath the target file path
     * @throws ConfigurationException if writing fails
     */
    public void writeProperties(Properties properties, Path filePath)
            throws ConfigurationException {
        Objects.requireNonNull(properties, "Properties cannot be null");
        Objects.requireNonNull(filePath, "File path cannot be null");

        try (OutputStream output = Files.newOutputStream(filePath);
             BufferedOutputStream buffered = new BufferedOutputStream(output)) {

            properties.store(buffered, "Generated configuration");

        } catch (IOException e) {
            logger.error("Failed to write properties to: {}", filePath, e);
            throw new ConfigurationException("Failed to write configuration", e);
        }
    }
}
```

**Bad example:**

```java
// AVOID: Poor resource management
public class BadResourceManager {

    // BAD: Manual resource management prone to leaks
    public String readFileContent(String filePath) throws Exception {
        FileInputStream fis = null;
        BufferedReader reader = null;

        try {
            fis = new FileInputStream(filePath);
            reader = new BufferedReader(new InputStreamReader(fis));

            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            return content.toString();

        } catch (Exception e) {
            throw new Exception("File read failed", e);
        } finally {
            // BAD: Resource cleanup can fail silently
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // Swallowed exception - bad practice
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // Another swallowed exception
                }
            }
        }
    }

    // BAD: No resource management at all
    public void executeQuery(String query) throws Exception {
        Connection connection = getConnection();
        PreparedStatement statement = connection.prepareStatement(query);
        ResultSet resultSet = statement.executeQuery();

        // Process results...

        // TERRIBLE: Resources never closed - guaranteed leak
    }

    // BAD: Inconsistent resource management
    public void writeProperties(Properties props, String filePath) throws Exception {
        FileOutputStream fos = new FileOutputStream(filePath);
        props.store(fos, "Config");
        fos.close(); // Only closed on success path
    }
}
```

### Example 3: Secure Exception Handling

Title: Protect Sensitive Information While Enabling Debugging
Description: Handle exceptions securely by logging detailed diagnostic information for developers while providing only generic, safe error messages to users. Never expose sensitive system details, file paths, database schemas, or internal implementation details in user-facing error messages.

**Good example:**

```java
// GOOD: Secure exception handling with proper information separation
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SecureService {
    private static final Logger logger = LoggerFactory.getLogger(SecureService.class);

    /**
     * Processes user authentication securely.
     *
     * @param username the username to authenticate
     * @param password the password to verify
     * @return authentication result
     * @throws AuthenticationException if authentication fails
     */
    public AuthResult authenticate(String username, String password) throws AuthenticationException {
        try {
            validateCredentials(username, password);
            User user = userRepository.findByUsername(username);

            if (user == null || !passwordEncoder.matches(password, user.getHashedPassword())) {
                // Log detailed info for security monitoring
                logger.warn("Authentication failed for username: {} from IP: {}",
                           username, getCurrentClientIP());

                // Generic message - don't reveal which part failed
                throw new AuthenticationException("Invalid credentials");
            }

            logger.info("Successful authentication for user: {}", username);
            return new AuthResult(user, generateToken(user));

        } catch (DatabaseException e) {
            // Log technical details for developers
            logger.error("Database error during authentication for user: {}", username, e);

            // Don't expose database details to user
            throw new AuthenticationException("Authentication service temporarily unavailable");

        } catch (Exception e) {
            // Log unexpected errors with full context
            logger.error("Unexpected error during authentication for user: {}", username, e);

            // Generic error message
            throw new AuthenticationException("Authentication failed");
        }
    }

    /**
     * Processes sensitive data with secure error handling.
     *
     * @param dataId the identifier of data to process
     * @return processing result
     * @throws ProcessingException if processing fails
     */
    public ProcessingResult processData(String dataId) throws ProcessingException {
        try {
            validateDataAccess(dataId);
            SensitiveData data = dataRepository.findById(dataId);

            return performProcessing(data);

        } catch (UnauthorizedException e) {
            // Log security event with context
            logger.warn("Unauthorized access attempt to data: {} by user: {}",
                       dataId, getCurrentUser(), e);

            // Standard security message
            throw new ProcessingException("Access denied", ErrorCode.FORBIDDEN);

        } catch (ValidationException e) {
            // Log validation failure details
            logger.debug("Validation failed for data: {}, reason: {}", dataId, e.getMessage());

            // Safe validation message
            throw new ProcessingException("Invalid data format", ErrorCode.BAD_REQUEST);

        } catch (SystemException e) {
            // Log system errors with correlation ID for tracking
            String correlationId = generateCorrelationId();
            logger.error("System error processing data: {} [correlation: {}]", dataId, correlationId, e);

            // Generic error with correlation ID for support
            throw new ProcessingException("System error occurred. Reference: " + correlationId,
                                        ErrorCode.INTERNAL_ERROR);
        }
    }

    // Secure error response builder
    public ErrorResponse buildErrorResponse(ProcessingException e, String requestId) {
        return ErrorResponse.builder()
            .message(e.getMessage()) // Safe message only
            .errorCode(e.getErrorCode().getCode())
            .timestamp(Instant.now())
            .requestId(requestId) // For tracking, not sensitive
            .build();
    }
}

// Safe error codes enum
public enum ErrorCode {
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_ERROR(500, "Internal Server Error");

    private final int httpStatus;
    private final String message;

    ErrorCode(int httpStatus, String message) {
        this.httpStatus = httpStatus;
        this.message = message;
    }

    public int getHttpStatus() { return httpStatus; }
    public String getMessage() { return message; }
    public String getCode() { return name(); }
}
```

**Bad example:**

```java
// AVOID: Insecure exception handling that exposes sensitive information
public class InsecureService {

    // BAD: Exposing sensitive system information
    public AuthResult authenticate(String username, String password) throws Exception {
        try {
            User user = userRepository.findByUsername(username);

            if (user == null) {
                // BAD: Reveals that username doesn't exist
                throw new Exception("User '" + username + "' not found in database table 'users'");
            }

            if (!user.getPassword().equals(password)) {
                // BAD: Reveals that username exists but password is wrong
                throw new Exception("Invalid password for user '" + username + "'");
            }

            return new AuthResult(user, generateToken(user));

        } catch (SQLException e) {
            // TERRIBLE: Exposing database connection details
            throw new Exception("Database connection failed to host db.internal.company.com:5432, " +
                              "database 'userdb', table 'users': " + e.getMessage(), e);
        }
    }

    // BAD: Exposing full stack traces to users
    public ProcessingResult processData(String dataId) throws Exception {
        try {
            // Processing logic...
            return performProcessing(dataId);
        } catch (Exception e) {
            // TERRIBLE: Full stack trace in response
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);

            throw new Exception("Processing failed:\n" + sw.toString());
        }
    }

    // BAD: Logging sensitive data
    public void processPayment(PaymentRequest request) throws Exception {
        try {
            // Process payment...
        } catch (Exception e) {
            // TERRIBLE: Logging sensitive payment information
            System.out.println("Payment failed for card: " + request.getCardNumber() +
                             ", CVV: " + request.getCvv() +
                             ", amount: " + request.getAmount());
            e.printStackTrace(); // Stack trace in logs

            // TERRIBLE: Exposing sensitive details in exception
            throw new Exception("Payment failed for card ending in " +
                              request.getCardNumber().substring(12) +
                              " with error: " + e.getMessage());
        }
    }

    // BAD: Different error messages reveal system state
    public UserProfile getUserProfile(String userId) throws Exception {
        User user = userDatabase.findById(userId);

        if (user == null) {
            throw new Exception("User with ID " + userId + " does not exist in system");
        }

        if (!user.isActive()) {
            throw new Exception("User account " + userId + " is deactivated");
        }

        if (user.getProfile() == null) {
            throw new Exception("User " + userId + " has no profile data in profile_table");
        }

        // This reveals information about system state and database structure
        return user.getProfile();
    }
}
```

### Example 4: Exception Chaining and Context Preservation

Title: Maintain Full Error Context for Effective Debugging
Description: Use exception chaining to preserve the original exception context while adding higher-level semantic meaning. This provides the full error context needed for debugging while allowing different layers of the application to handle errors appropriately.

**Good example:**

```java
// GOOD: Proper exception chaining with context preservation
public class LayeredService {
    private static final Logger logger = LoggerFactory.getLogger(LayeredService.class);

    // Custom exception hierarchy with chaining support
    public static class ServiceException extends Exception {
        public ServiceException(String message) {
            super(message);
        }

        public ServiceException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    public static class DataAccessException extends ServiceException {
        public DataAccessException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    public static class BusinessLogicException extends ServiceException {
        public BusinessLogicException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    // Data layer - preserves original database exceptions
    public User findUserById(Long userId) throws DataAccessException {
        try {
            return userRepository.findById(userId);

        } catch (SQLException e) {
            // Chain the SQL exception with business context
            throw new DataAccessException("Failed to retrieve user with ID: " + userId, e);

        } catch (ConnectionException e) {
            // Chain connection issues
            throw new DataAccessException("Database connection failed while fetching user: " + userId, e);
        }
    }

    // Service layer - adds business context while preserving technical details
    public UserProfile getUserProfile(Long userId) throws BusinessLogicException {
        try {
            if (userId == null || userId <= 0) {
                throw new IllegalArgumentException("User ID must be positive, was: " + userId);
            }

            User user = findUserById(userId);

            if (user == null) {
                throw new UserNotFoundException("User not found with ID: " + userId);
            }

            if (!user.isActive()) {
                throw new UserInactiveException("User account is inactive: " + userId);
            }

            return buildUserProfile(user);

        } catch (DataAccessException e) {
            // Chain data access errors with business context
            throw new BusinessLogicException("Unable to retrieve user profile for ID: " + userId, e);

        } catch (IllegalArgumentException e) {
            // Chain validation errors
            throw new BusinessLogicException("Invalid user ID provided: " + userId, e);

        } catch (Exception e) {
            // Chain unexpected errors
            logger.error("Unexpected error retrieving user profile: {}", userId, e);
            throw new BusinessLogicException("Unexpected error occurred while retrieving user profile", e);
        }
    }

    // Controller layer - handles service exceptions appropriately
    public ResponseEntity<UserProfileDto> handleGetUserProfile(Long userId) {
        try {
            UserProfile profile = getUserProfile(userId);
            return ResponseEntity.ok(convertToDto(profile));

        } catch (BusinessLogicException e) {
            // Log the full chain for debugging
            logger.error("Business logic error for user profile request: {}", userId, e);

            // Determine response based on root cause
            Throwable rootCause = getRootCause(e);

            if (rootCause instanceof UserNotFoundException) {
                return ResponseEntity.notFound().build();
            } else if (rootCause instanceof UserInactiveException) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            } else if (rootCause instanceof IllegalArgumentException) {
                return ResponseEntity.badRequest().build();
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
        }
    }

    // Utility to find root cause in exception chain
    private Throwable getRootCause(Throwable throwable) {
        Throwable cause = throwable;
        while (cause.getCause() != null && cause.getCause() != cause) {
            cause = cause.getCause();
        }
        return cause;
    }

    // Example of rethrowing with additional context
    public void processUserData(User user) throws ProcessingException {
        try {
            validateUser(user);
            transformUserData(user);
            persistUser(user);

        } catch (ValidationException e) {
            // Add context while preserving original exception
            throw new ProcessingException("User data validation failed for user: " + user.getId(), e);

        } catch (TransformationException e) {
            // Chain transformation errors
            throw new ProcessingException("Failed to transform user data: " + user.getId(), e);

        } catch (PersistenceException e) {
            // Chain persistence errors
            throw new ProcessingException("Failed to save user data: " + user.getId(), e);
        }
    }
}
```

**Bad example:**

```java
// AVOID: Poor exception handling that loses context
public class BadLayeredService {

    // BAD: Losing original exception context
    public User findUserById(Long userId) throws Exception {
        try {
            return userRepository.findById(userId);
        } catch (SQLException e) {
            // TERRIBLE: Original exception is lost
            throw new Exception("Database error");
        }
    }

    // BAD: Generic exception handling loses specific error information
    public UserProfile getUserProfile(Long userId) throws Exception {
        try {
            User user = findUserById(userId);
            return buildUserProfile(user);
        } catch (Exception e) {
            // BAD: All specific error context is lost
            throw new Exception("Failed to get user profile");
        }
    }

    // BAD: Swallowing exceptions entirely
    public UserProfile getUserProfileSilent(Long userId) {
        try {
            User user = findUserById(userId);
            return buildUserProfile(user);
        } catch (Exception e) {
            // TERRIBLE: Exception completely swallowed
            e.printStackTrace(); // Poor logging
            return null; // Hiding the error
        }
    }

    // BAD: Creating new exceptions without chaining
    public void processUserData(User user) throws ProcessingException {
        try {
            validateUser(user);
            transformUserData(user);
            persistUser(user);
        } catch (ValidationException e) {
            // BAD: Original exception information is lost
            throw new ProcessingException("Validation failed");
        } catch (Exception e) {
            // BAD: Generic handling without context
            throw new ProcessingException("Processing failed");
        }
    }

    // BAD: Catching and rethrowing without adding value
    public String processRequest(String request) throws ServiceException {
        try {
            return businessLogic.process(request);
        } catch (BusinessException e) {
            // BAD: Catching just to rethrow without adding context
            throw e;
        } catch (Exception e) {
            // BAD: Unnecessary wrapping without semantic value
            throw new ServiceException(e.getMessage());
        }
    }

    // BAD: Multiple exception handling points that lose context
    public Result performComplexOperation(String input) {
        try {
            String processed = preprocessInput(input);

            try {
                String validated = validateInput(processed);

                try {
                    return executeOperation(validated);
                } catch (ExecutionException e) {
                    // BAD: Nested try-catch losing context
                    return Result.failure("Execution failed");
                }
            } catch (ValidationException e) {
                // BAD: Each level loses more context
                return Result.failure("Validation failed");
            }
        } catch (Exception e) {
            // BAD: Original error completely lost
            return Result.failure("Operation failed");
        }
    }
}
```

### Example 5: Thread Interruption and Concurrent Exception Handling

Title: Handle InterruptedException and Concurrent Operations Properly
Description: Handle InterruptedException correctly by restoring the interrupted status and taking appropriate action. In concurrent code, ensure exception handling doesn't break thread safety or leave threads in inconsistent states.

**Good example:**

```java
// GOOD: Proper thread interruption and concurrent exception handling
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConcurrentProcessor {
    private static final Logger logger = LoggerFactory.getLogger(ConcurrentProcessor.class);
    private final ExecutorService executor = Executors.newFixedThreadPool(10);
    private final Lock processLock = new ReentrantLock();

    /**
     * Processes tasks with proper interruption handling.
     *
     * @param tasks the tasks to process
     * @return processing results
     * @throws ProcessingException if processing fails
     * @throws InterruptedException if thread is interrupted
     */
    public List<Result> processTasks(List<Task> tasks) throws ProcessingException, InterruptedException {
        List<Future<Result>> futures = new ArrayList<>();

        try {
            // Submit tasks
            for (Task task : tasks) {
                Future<Result> future = executor.submit(() -> processTask(task));
                futures.add(future);
            }

            // Collect results with proper timeout
            List<Result> results = new ArrayList<>();
            for (Future<Result> future : futures) {
                try {
                    // Use timeout to avoid indefinite blocking
                    Result result = future.get(30, TimeUnit.SECONDS);
                    results.add(result);

                } catch (InterruptedException e) {
                    // Restore interrupted status immediately
                    Thread.currentThread().interrupt();

                    // Cancel remaining tasks
                    cancelRemainingTasks(futures);

                    logger.info("Task processing interrupted");
                    throw e; // Re-throw to caller

                } catch (TimeoutException e) {
                    logger.warn("Task processing timed out, cancelling task");
                    future.cancel(true); // Interrupt if necessary
                    throw new ProcessingException("Task processing timed out", e);

                } catch (ExecutionException e) {
                    Throwable cause = e.getCause();
                    logger.error("Task execution failed", cause);
                    throw new ProcessingException("Task execution failed", cause);
                }
            }

            return results;

        } finally {
            // Clean up any remaining futures
            cancelRemainingTasks(futures);
        }
    }

    /**
     * Processes a single task with proper interruption checking.
     *
     * @param task the task to process
     * @return processing result
     * @throws ProcessingException if processing fails
     */
    private Result processTask(Task task) throws ProcessingException {
        try {
            // Check interruption status before starting
            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException("Thread interrupted before processing");
            }

            // Step 1: Validate task
            validateTask(task);

            // Check interruption between steps
            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException("Thread interrupted during validation");
            }

            // Step 2: Process with simulated work
            Thread.sleep(100); // Simulated processing time

            // Step 3: Generate result
            return new Result(task.getId(), "Processed successfully");

        } catch (InterruptedException e) {
            // Restore interrupted status
            Thread.currentThread().interrupt();

            logger.info("Task processing interrupted: {}", task.getId());
            throw new ProcessingException("Task processing was interrupted", e);

        } catch (Exception e) {
            logger.error("Unexpected error processing task: {}", task.getId(), e);
            throw new ProcessingException("Failed to process task: " + task.getId(), e);
        }
    }

    /**
     * Thread-safe method with proper lock exception handling.
     *
     * @param data the data to process safely
     * @throws ProcessingException if processing fails
     */
    public void processWithLock(String data) throws ProcessingException {
        boolean lockAcquired = false;

        try {
            // Try to acquire lock with timeout
            lockAcquired = processLock.tryLock(5, TimeUnit.SECONDS);

            if (!lockAcquired) {
                throw new ProcessingException("Could not acquire processing lock within timeout");
            }

            // Critical section - process data
            performCriticalProcessing(data);

        } catch (InterruptedException e) {
            // Restore interrupted status
            Thread.currentThread().interrupt();

            logger.info("Lock acquisition interrupted");
            throw new ProcessingException("Processing interrupted while waiting for lock", e);

        } catch (Exception e) {
            logger.error("Error during locked processing", e);
            throw new ProcessingException("Processing failed", e);

        } finally {
            // Always release lock if acquired
            if (lockAcquired) {
                processLock.unlock();
            }
        }
    }

    /**
     * Graceful shutdown with proper exception handling.
     */
    public void shutdown() {
        try {
            executor.shutdown();

            if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                logger.warn("Executor did not terminate gracefully, forcing shutdown");
                executor.shutdownNow();

                // Wait a bit more for tasks to respond to being cancelled
                if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    logger.error("Executor did not terminate after forced shutdown");
                }
            }

        } catch (InterruptedException e) {
            // Restore interrupted status
            Thread.currentThread().interrupt();

            logger.warn("Shutdown interrupted, forcing immediate shutdown");
            executor.shutdownNow();
        }
    }

    private void cancelRemainingTasks(List<Future<Result>> futures) {
        for (Future<Result> future : futures) {
            if (!future.isDone()) {
                future.cancel(true);
            }
        }
    }

    private void validateTask(Task task) throws ValidationException {
        if (task == null || task.getId() == null) {
            throw new ValidationException("Invalid task: null task or ID");
        }
    }

    private void performCriticalProcessing(String data) {
        // Simulate critical processing
        logger.debug("Processing data in critical section: {}", data);
    }
}
```

**Bad example:**

```java
// AVOID: Poor thread interruption and concurrent exception handling
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class BadConcurrentProcessor {
    private final ExecutorService executor = Executors.newFixedThreadPool(10);

    // BAD: Not handling InterruptedException properly
    public List<Result> processTasks(List<Task> tasks) throws Exception {
        List<Future<Result>> futures = new ArrayList<>();

        for (Task task : tasks) {
            Future<Result> future = executor.submit(() -> processTask(task));
            futures.add(future);
        }

        List<Result> results = new ArrayList<>();
        for (Future<Result> future : futures) {
            try {
                results.add(future.get());
            } catch (InterruptedException e) {
                // BAD: Ignoring interruption
                System.out.println("Interrupted, but continuing anyway");
                // NOT restoring interrupted status
            } catch (Exception e) {
                // BAD: Generic exception handling
                throw new Exception("Something failed");
            }
        }

        return results;
    }

    // BAD: Poor interruption handling in long-running task
    private Result processTask(Task task) {
        try {
            // BAD: Not checking interruption status
            for (int i = 0; i < 1000; i++) {
                // Long-running work without interruption checks
                Thread.sleep(10);
                // Should check Thread.currentThread().isInterrupted()
            }

            return new Result(task.getId(), "Processed");

        } catch (InterruptedException e) {
            // BAD: Swallowing InterruptedException
            return new Result(task.getId(), "Failed");
        }
    }

    // BAD: Poor lock exception handling
    public void processWithLock(String data) {
        try {
            lock.lock(); // BAD: No timeout, can block forever

            // Process data

        } catch (Exception e) {
            // BAD: Generic exception handling doesn't distinguish lock issues
            e.printStackTrace();
        } finally {
            // BAD: Releasing lock even if never acquired
            lock.unlock(); // Could throw IllegalMonitorStateException
        }
    }

    // BAD: Poor shutdown handling
    public void shutdown() {
        executor.shutdown();

        try {
            executor.awaitTermination(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // BAD: Not handling interruption during shutdown
        }

        // BAD: No forced shutdown if graceful shutdown fails
    }

    // BAD: Race condition in exception handling
    private volatile boolean processing = false;

    public void unsafeProcess(String data) {
        try {
            processing = true;

            // Some processing...

        } catch (Exception e) {
            // BAD: Exception handling has race condition
            if (processing) { // Could be changed by another thread
                processing = false;
            }
        }
        // BAD: processing flag might not be reset if no exception
    }

    // BAD: Not preserving interrupted status in utility method
    public void waitForCondition() {
        while (!conditionMet()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // BAD: Not restoring interrupted status
                break; // Exits but doesn't signal interruption to caller
            }
        }
    }
}
```

### Example 6: Custom Exception Design and Documentation

Title: Create Meaningful Exception Hierarchies with Proper Documentation
Description: Design custom exception hierarchies that provide semantic meaning and enable appropriate handling at different application layers. Document exceptions thoroughly with @throws tags and provide clear guidance on when and why they are thrown.

**Good example:**

```java
// GOOD: Well-designed custom exception hierarchy with proper documentation
/**
 * Base exception for all business-related errors in the user management system.
 * This is a checked exception to force explicit handling of business logic failures.
 */
public class UserManagementException extends Exception {
    private final ErrorCode errorCode;
    private final String userContext;

    public UserManagementException(String message, ErrorCode errorCode) {
        super(message);
        this.errorCode = errorCode;
        this.userContext = null;
    }

    public UserManagementException(String message, ErrorCode errorCode, String userContext) {
        super(message);
        this.errorCode = errorCode;
        this.userContext = userContext;
    }

    public UserManagementException(String message, ErrorCode errorCode, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
        this.userContext = null;
    }

    public UserManagementException(String message, ErrorCode errorCode, String userContext, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
        this.userContext = userContext;
    }

    public ErrorCode getErrorCode() { return errorCode; }
    public String getUserContext() { return userContext; }
}

/**
 * Thrown when user validation fails due to invalid input data.
 * This is a specific exception that indicates the client provided invalid data.
 */
public class UserValidationException extends UserManagementException {
    private final List<String> validationErrors;

    public UserValidationException(String message, List<String> validationErrors) {
        super(message, ErrorCode.VALIDATION_FAILED);
        this.validationErrors = new ArrayList<>(validationErrors);
    }

    public UserValidationException(String message, String userContext, List<String> validationErrors) {
        super(message, ErrorCode.VALIDATION_FAILED, userContext);
        this.validationErrors = new ArrayList<>(validationErrors);
    }

    public List<String> getValidationErrors() {
        return new ArrayList<>(validationErrors);
    }
}

/**
 * Thrown when a requested user cannot be found in the system.
 * This typically results in a 404 response in web applications.
 */
public class UserNotFoundException extends UserManagementException {
    private final String requestedUserId;

    public UserNotFoundException(String userId) {
        super("User not found: " + userId, ErrorCode.USER_NOT_FOUND, userId);
        this.requestedUserId = userId;
    }

    public UserNotFoundException(String userId, Throwable cause) {
        super("User not found: " + userId, ErrorCode.USER_NOT_FOUND, userId, cause);
        this.requestedUserId = userId;
    }

    public String getRequestedUserId() { return requestedUserId; }
}

/**
 * Thrown when user operations fail due to insufficient permissions.
 * This indicates an authorization failure after successful authentication.
 */
public class UserPermissionException extends UserManagementException {
    private final String requiredPermission;
    private final String currentUserRole;

    public UserPermissionException(String requiredPermission, String currentUserRole) {
        super("Insufficient permissions. Required: " + requiredPermission + ", Current role: " + currentUserRole,
              ErrorCode.INSUFFICIENT_PERMISSIONS);
        this.requiredPermission = requiredPermission;
        this.currentUserRole = currentUserRole;
    }

    public String getRequiredPermission() { return requiredPermission; }
    public String getCurrentUserRole() { return currentUserRole; }
}

/**
 * Service class demonstrating proper exception usage and documentation.
 */
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    /**
     * Creates a new user in the system.
     *
     * @param userRequest the user creation request containing user details
     * @param createdBy the ID of the user creating this user
     * @return the created user with generated ID
     * @throws UserValidationException if the user request contains invalid data
     * @throws UserPermissionException if the creating user lacks permission to create users
     * @throws UserManagementException if user creation fails due to system errors
     * @throws IllegalArgumentException if userRequest or createdBy is null
     */
    public User createUser(UserCreateRequest userRequest, String createdBy)
            throws UserValidationException, UserPermissionException, UserManagementException {

        // Input validation with specific exceptions
        if (userRequest == null) {
            throw new IllegalArgumentException("User request cannot be null");
        }
        if (createdBy == null) {
            throw new IllegalArgumentException("Created by user ID cannot be null");
        }

        try {
            // Validate permissions
            validateCreateUserPermission(createdBy);

            // Validate user data
            List<String> validationErrors = validateUserRequest(userRequest);
            if (!validationErrors.isEmpty()) {
                throw new UserValidationException("User validation failed",
                                                userRequest.getEmail(), validationErrors);
            }

            // Check for duplicate email
            if (userRepository.existsByEmail(userRequest.getEmail())) {
                throw new UserValidationException("Email already exists",
                                                userRequest.getEmail(),
                                                List.of("Email address is already registered"));
            }

            // Create user
            User user = new User(userRequest);
            user.setCreatedBy(createdBy);
            user.setCreatedAt(Instant.now());

            return userRepository.save(user);

        } catch (PermissionCheckException e) {
            throw new UserPermissionException("CREATE_USER", getCurrentUserRole(createdBy));

        } catch (DatabaseException e) {
            logger.error("Database error creating user for request: {}", userRequest.getEmail(), e);
            throw new UserManagementException("Failed to create user due to system error",
                                           ErrorCode.SYSTEM_ERROR, userRequest.getEmail(), e);

        } catch (Exception e) {
            logger.error("Unexpected error creating user: {}", userRequest.getEmail(), e);
            throw new UserManagementException("Unexpected error during user creation",
                                           ErrorCode.SYSTEM_ERROR, userRequest.getEmail(), e);
        }
    }

    /**
     * Retrieves a user by their ID.
     *
     * @param userId the ID of the user to retrieve
     * @param requestingUserId the ID of the user making the request
     * @return the requested user
     * @throws UserNotFoundException if no user exists with the given ID
     * @throws UserPermissionException if the requesting user cannot access the requested user
     * @throws UserManagementException if retrieval fails due to system errors
     * @throws IllegalArgumentException if userId or requestingUserId is null or invalid
     */
    public User getUserById(String userId, String requestingUserId)
            throws UserNotFoundException, UserPermissionException, UserManagementException {

        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("User ID cannot be null or empty");
        }
        if (requestingUserId == null || requestingUserId.trim().isEmpty()) {
            throw new IllegalArgumentException("Requesting user ID cannot be null or empty");
        }

        try {
            // Check if user exists
            User user = userRepository.findById(userId);
            if (user == null) {
                throw new UserNotFoundException(userId);
            }

            // Check permissions
            if (!canAccessUser(requestingUserId, userId)) {
                throw new UserPermissionException("READ_USER", getCurrentUserRole(requestingUserId));
            }

            return user;

        } catch (UserNotFoundException | UserPermissionException e) {
            // Re-throw business exceptions as-is
            throw e;

        } catch (DatabaseException e) {
            logger.error("Database error retrieving user: {}", userId, e);
            throw new UserManagementException("Failed to retrieve user due to system error",
                                           ErrorCode.SYSTEM_ERROR, userId, e);

        } catch (Exception e) {
            logger.error("Unexpected error retrieving user: {}", userId, e);
            throw new UserManagementException("Unexpected error during user retrieval",
                                           ErrorCode.SYSTEM_ERROR, userId, e);
        }
    }

    private List<String> validateUserRequest(UserCreateRequest request) {
        List<String> errors = new ArrayList<>();

        if (request.getEmail() == null || !isValidEmail(request.getEmail())) {
            errors.add("Invalid email address");
        }

        if (request.getFirstName() == null || request.getFirstName().trim().isEmpty()) {
            errors.add("First name is required");
        }

        if (request.getLastName() == null || request.getLastName().trim().isEmpty()) {
            errors.add("Last name is required");
        }

        return errors;
    }

    private boolean isValidEmail(String email) {
        return email.contains("@") && email.contains(".");
    }

    private void validateCreateUserPermission(String userId) throws PermissionCheckException {
        // Implementation for permission checking
    }

    private String getCurrentUserRole(String userId) {
        // Implementation to get user role
        return "USER";
    }

    private boolean canAccessUser(String requestingUserId, String targetUserId) {
        // Implementation for access control
        return requestingUserId.equals(targetUserId);
    }
}

/**
 * Error codes for categorizing different types of user management failures.
 */
public enum ErrorCode {
    VALIDATION_FAILED("VALIDATION_FAILED", "Input validation failed"),
    USER_NOT_FOUND("USER_NOT_FOUND", "Requested user not found"),
    INSUFFICIENT_PERMISSIONS("INSUFFICIENT_PERMISSIONS", "Insufficient permissions for operation"),
    DUPLICATE_EMAIL("DUPLICATE_EMAIL", "Email address already exists"),
    SYSTEM_ERROR("SYSTEM_ERROR", "System error occurred");

    private final String code;
    private final String description;

    ErrorCode(String code, String description) {
        this.code = code;
        this.description = description;
    }

    public String getCode() { return code; }
    public String getDescription() { return description; }
}
```

**Bad example:**

```java
// AVOID: Poor custom exception design and documentation
// BAD: Generic exception without semantic meaning
public class UserException extends Exception {
    public UserException(String message) {
        super(message);
    }
}

// BAD: Runtime exception for recoverable business logic
public class UserError extends RuntimeException {
    public UserError() {
        super();
    }
}

// BAD: Exception without context or useful information
public class ValidationFailed extends Exception {
}

public class BadUserService {

    // BAD: Poor exception documentation and handling
    public User createUser(UserRequest request) throws Exception {
        // BAD: Generic throws Exception clause

        if (request.getEmail() == null) {
            // BAD: No context about what validation failed
            throw new Exception("Invalid");
        }

        try {
            return userRepository.save(new User(request));
        } catch (Exception e) {
            // BAD: Catching and rethrowing generic exception
            throw new Exception("Failed");
        }
    }

    // BAD: No exception documentation
    public User getUserById(String userId) throws UserException {
        User user = userRepository.findById(userId);

        if (user == null) {
            // BAD: No context about which user wasn't found
            throw new UserException("Not found");
        }

        return user;
    }

    // BAD: Using runtime exceptions for business logic
    public void deleteUser(String userId) {
        User user = userRepository.findById(userId);

        if (user == null) {
            // BAD: Runtime exception for expected business condition
            throw new RuntimeException("User doesn't exist: " + userId);
        }

        if (user.hasActiveOrders()) {
            // BAD: Different exception types for similar business conditions
            throw new IllegalStateException("Cannot delete user with active orders");
        }

        userRepository.delete(user);
    }

    // BAD: Inconsistent exception handling
    public List<User> getUsers(String department) throws Exception {
        try {
            if (department == null) {
                // BAD: IllegalArgumentException for some validations
                throw new IllegalArgumentException("Department required");
            }

            List<User> users = userRepository.findByDepartment(department);

            if (users.isEmpty()) {
                // BAD: Different exception type for similar condition
                throw new UserException("No users found");
            }

            return users;

        } catch (DatabaseException e) {
            // BAD: Converting specific exception to generic
            throw new Exception("Database problem");
        }
    }

    // BAD: No exception hierarchy or categorization
    public void updateUserEmail(String userId, String newEmail) throws Exception {
        // No validation...

        try {
            User user = userRepository.findById(userId);
            user.setEmail(newEmail);
            userRepository.save(user);
        } catch (Exception e) {
            // BAD: All errors become the same generic exception
            throw new Exception("Update failed: " + e.getMessage());
        }
    }

    // BAD: Mixing checked and unchecked exceptions inconsistently
    public User authenticateUser(String email, String password)
            throws UserException { // Checked exception

        if (email == null) {
            // BAD: RuntimeException mixed with checked exceptions
            throw new NullPointerException("Email cannot be null");
        }

        User user = findByEmail(email);

        if (user == null) {
            // BAD: Inconsistent exception types for authentication
            throw new UserException("Authentication failed");
        }

        if (!passwordMatches(password, user.getPasswordHash())) {
            // BAD: Different exception for same logical condition
            throw new SecurityException("Invalid password");
        }

        return user;
    }
}
```


### Example 7: Use Exceptions Only for Exceptional Conditions

Title: Don't use exceptions for ordinary control flow
Description: Exceptions should be used for exceptional conditions, not for normal program flow. They are expensive and make code harder to understand. Use regular control structures for predictable conditions.

**Good example:**

```java
// GOOD: Normal control flow for array processing
public class NumberProcessor {
    public void processNumbers(int[] numbers) {
        for (int number : numbers) {  // Normal iteration
            if (isValid(number)) {    // Normal condition checking
                process(number);
            } else {
                logger.warn("Skipping invalid number: {}", number);
            }
        }
    }

    private boolean isValid(int number) {
        return number >= 0 && number <= 1000;
    }

    private void process(int number) {
        // Process the number
        logger.info("Processing: {}", number);
    }
}
```

**Bad example:**

```java
// AVOID: Using exceptions for normal control flow
public class NumberProcessor {
    public void processNumbers(int[] numbers) {
        try {
            int i = 0;
            while (true) {  // Using exception for loop termination
                process(numbers[i++]);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            // Using exception for normal control flow - bad!
        }
    }

    private void process(int number) {
        System.out.println("Processing: " + number);
    }
}
```

### Example 8: Use Checked Exceptions for Recoverable Conditions and Runtime Exceptions for Programming Errors

Title: Choose the right type of exception for the situation
Description: Checked exceptions force the caller to handle recoverable conditions, while runtime exceptions indicate programming errors that should be fixed in code. Use checked exceptions for conditions the caller can reasonably recover from.

**Good example:**

```java
// GOOD: Appropriate exception types for different scenarios
public class FileProcessor {

    /**
     * Processes a file. Throws checked exception for recoverable I/O issues.
     *
     * @param filename the file to process
     * @throws FileProcessingException if file cannot be processed (recoverable)
     */
    public void processFile(String filename) throws FileProcessingException {
        Objects.requireNonNull(filename, "Filename cannot be null");

        try {
            List<String> lines = Files.readAllLines(Paths.get(filename));
            lines.forEach(this::processLine);
        } catch (IOException e) {
            // Wrap in domain-specific checked exception - caller can retry
            throw new FileProcessingException("Failed to process file: " + filename, e);
        }
    }

    /**
     * Validates input parameters. Throws runtime exception for programming errors.
     *
     * @param input the input to validate
     * @throws IllegalArgumentException if input is invalid (programming error)
     */
    public void validateInput(String input) {
        if (input == null) {
            // Programming error - should never happen in correct code
            throw new IllegalArgumentException("Input cannot be null");
        }
        if (input.trim().isEmpty()) {
            // Programming error - caller should validate before calling
            throw new IllegalArgumentException("Input cannot be empty");
        }
    }

    private void processLine(String line) {
        // Processing logic
    }
}

// Custom checked exception for recoverable conditions
class FileProcessingException extends Exception {
    public FileProcessingException(String message, Throwable cause) {
        super(message, cause);
    }
}
```

**Bad example:**

```java
// AVOID: Wrong exception types for the situation
public class FileProcessor {

    // BAD: Using checked exception for programming error
    public void validateInput(String input) throws ValidationException {
        if (input == null) {
            throw new ValidationException("Input cannot be null");  // Should be RuntimeException
        }
    }

    // BAD: Using runtime exception for recoverable condition
    public void processFile(String filename) {
        try {
            Files.readAllLines(Paths.get(filename));
        } catch (IOException e) {
            // Should be checked exception so caller can handle
            throw new RuntimeException("File processing failed", e);
        }
    }
}
```

### Example 9: Favor the Use of Standard Exceptions

Title: Use standard Java exceptions when appropriate
Description: Standard exceptions are familiar to developers and have clear semantics. Don't create custom exceptions when standard ones sufficiently express the error condition.

**Good example:**

```java
// GOOD: Using standard exceptions with descriptive messages
public class Calculator {

    public double divide(double dividend, double divisor) {
        if (divisor == 0.0) {
            throw new ArithmeticException("Division by zero is not allowed");  // Standard exception
        }
        return dividend / divisor;
    }

    public int getElement(List<Integer> list, int index) {
        Objects.requireNonNull(list, "List cannot be null");

        if (index < 0 || index >= list.size()) {
            throw new IndexOutOfBoundsException(
                String.format("Index %d is out of bounds for list of size %d", index, list.size())
            );
        }
        return list.get(index);
    }

    public void processPositiveNumber(int number) {
        if (number <= 0) {
            throw new IllegalArgumentException("Number must be positive, was: " + number);
        }
        // Process the number
    }
}
```

**Bad example:**

```java
// AVOID: Custom exceptions when standard ones would suffice
public class Calculator {

    public double divide(double dividend, double divisor) {
        if (divisor == 0.0) {
            throw new DivisionByZeroException("Cannot divide by zero");  // Unnecessary custom exception
        }
        return dividend / divisor;
    }

    public int getElement(List<Integer> list, int index) {
        if (list == null) {
            throw new ListIsNullException("List cannot be null");  // Should use NullPointerException
        }
        if (index < 0 || index >= list.size()) {
            throw new InvalidIndexException("Bad index: " + index);  // Should use IndexOutOfBoundsException
        }
        return list.get(index);
    }
}

// Unnecessary custom exceptions
class DivisionByZeroException extends RuntimeException {
    public DivisionByZeroException(String message) { super(message); }
}

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

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

### Example 10: Include Failure-Capture Information in Detail Messages

Title: Provide detailed, actionable information in exception messages
Description: Exception messages should provide enough context to understand what went wrong and how to fix it. Include relevant parameter values, expected ranges, and specific failure conditions.

**Good example:**

```java
// GOOD: Detailed exception messages with context
public class BankAccount {
    private double balance;
    private final String accountNumber;
    private final String accountHolderName;

    public BankAccount(String accountNumber, String accountHolderName, double initialBalance) {
        this.accountNumber = Objects.requireNonNull(accountNumber, "Account number cannot be null");
        this.accountHolderName = Objects.requireNonNull(accountHolderName, "Account holder name cannot be null");

        if (initialBalance < 0) {
            throw new IllegalArgumentException(
                String.format("Initial balance cannot be negative. Account: %s, Attempted balance: %.2f",
                             accountNumber, initialBalance)
            );
        }
        this.balance = initialBalance;
    }

    public void withdraw(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException(
                String.format("Withdrawal amount must be positive. Account: %s, Attempted amount: %.2f",
                             accountNumber, amount)
            );
        }

        if (amount > balance) {
            throw new InsufficientFundsException(
                String.format("Insufficient funds for withdrawal. Account: %s, Current balance: %.2f, Requested: %.2f",
                             accountNumber, balance, amount)
            );
        }

        balance -= amount;
    }

    public void transfer(BankAccount toAccount, double amount) {
        Objects.requireNonNull(toAccount, "Destination account cannot be null");

        if (toAccount.accountNumber.equals(this.accountNumber)) {
            throw new IllegalArgumentException(
                String.format("Cannot transfer to the same account. Account number: %s", accountNumber)
            );
        }

        withdraw(amount); // This will validate amount and balance
        toAccount.deposit(amount);
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException(
                String.format("Deposit amount must be positive. Account: %s, Attempted amount: %.2f",
                             accountNumber, amount)
            );
        }
        balance += amount;
    }
}
```

**Bad example:**

```java
// AVOID: Vague exception messages without context
public class BankAccount {
    private double balance;
    private final String accountNumber;

    public void withdraw(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Invalid amount");  // Too vague
        }
        if (amount > balance) {
            throw new InsufficientFundsException("Not enough money");  // No specific details
        }
        balance -= amount;
    }

    public void transfer(BankAccount toAccount, double amount) {
        if (toAccount == null) {
            throw new IllegalArgumentException("Bad account");  // No context
        }
        if (toAccount.accountNumber.equals(this.accountNumber)) {
            throw new IllegalArgumentException("Error");  // Completely unhelpful
        }
        withdraw(amount);
        toAccount.deposit(amount);
    }
}
```

### Example 11: Don't Ignore Exceptions

Title: Always handle exceptions appropriately, never ignore them silently
Description: Ignoring exceptions can hide bugs and make debugging extremely difficult. Always log exceptions appropriately, handle them meaningfully, or re-throw them with additional context.

**Good example:**

```java
// GOOD: Proper exception handling without ignoring
public class FileManager {
    private static final Logger logger = LoggerFactory.getLogger(FileManager.class);

    public Optional<String> readFileContent(String filename) {
        Objects.requireNonNull(filename, "Filename cannot be null");

        try {
            return Optional.of(Files.readString(Paths.get(filename)));
        } catch (IOException e) {
            // Log the exception with context
            logger.warn("Failed to read file: {}", filename, e);
            return Optional.empty();  // Return meaningful result
        }
    }

    public void saveToFile(String filename, String content) throws FileOperationException {
        Objects.requireNonNull(filename, "Filename cannot be null");
        Objects.requireNonNull(content, "Content cannot be null");

        try {
            Files.writeString(Paths.get(filename), content);
            logger.info("Successfully saved content to file: {}", filename);
        } catch (IOException e) {
            // Re-throw as domain-specific exception with context
            throw new FileOperationException("Failed to save content to file: " + filename, e);
        }
    }

    public void cleanupTempFiles(List<String> tempFiles) {
        for (String tempFile : tempFiles) {
            try {
                Files.deleteIfExists(Paths.get(tempFile));
            } catch (IOException e) {
                // Log but continue with other files
                logger.warn("Failed to delete temporary file: {}", tempFile, e);
            }
        }
    }
}

class FileOperationException extends Exception {
    public FileOperationException(String message, Throwable cause) {
        super(message, cause);
    }
}
```

**Bad example:**

```java
// AVOID: Ignoring exceptions
public class FileManager {

    public String readFileContent(String filename) {
        try {
            return Files.readString(Paths.get(filename));
        } catch (IOException e) {
            // Silently ignoring exception - very bad!
        }
        return null;  // Caller has no idea what went wrong
    }

    public void saveToFile(String filename, String content) {
        try {
            Files.writeString(Paths.get(filename), content);
        } catch (IOException e) {
            // Empty catch block - hiding the problem
        }
    }

    public void processFiles(List<String> files) {
        for (String file : files) {
            try {
                processFile(file);
            } catch (Exception e) {
                // Ignoring all exceptions - could hide critical issues
                e.printStackTrace(); // Poor logging
            }
        }
    }
}
```

### Example 12: Testing Exception Scenarios Effectively

Title: Comprehensive patterns for testing exception handling
Description: Test exception scenarios thoroughly using AssertJ's fluent API for clear, maintainable test code. Verify both that exceptions are thrown when expected and that they contain appropriate messages and context.

**Good example:**

```java
// GOOD: Comprehensive exception testing with AssertJ
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class CalculatorExceptionTest {

    private final Calculator calculator = new Calculator();

    @Test
    @DisplayName("Should throw ArithmeticException when dividing by zero")
    void divide_byZero_throwsArithmeticException() {
        // Given
        double dividend = 10.0;
        double divisor = 0.0;

        // When & Then
        assertThatThrownBy(() -> calculator.divide(dividend, divisor))
            .isInstanceOf(ArithmeticException.class)
            .hasMessageContaining("Division by zero")
            .hasNoCause();
    }

    @Test
    @DisplayName("Should throw IllegalArgumentException for negative number validation")
    void processPositiveNumber_withNegative_throwsIllegalArgumentException() {
        // Given
        int negativeNumber = -5;

        // When & Then
        assertThatThrownBy(() -> calculator.processPositiveNumber(negativeNumber))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("Number must be positive")
            .hasMessageContaining("-5");
    }

    @Test
    @DisplayName("Should throw IndexOutOfBoundsException with detailed message")
    void getElement_withInvalidIndex_throwsIndexOutOfBoundsException() {
        // Given
        List<Integer> list = Arrays.asList(1, 2, 3);
        int invalidIndex = 5;

        // When & Then
        assertThatThrownBy(() -> calculator.getElement(list, invalidIndex))
            .isInstanceOf(IndexOutOfBoundsException.class)
            .hasMessageContaining("Index 5")
            .hasMessageContaining("size 3");
    }

    @Test
    @DisplayName("Should handle chained exceptions properly")
    void processFile_withIOError_throwsFileProcessingExceptionWithCause() {
        // Given
        FileProcessor processor = new FileProcessor();
        String nonExistentFile = "non-existent-file.txt";

        // When & Then
        assertThatThrownBy(() -> processor.processFile(nonExistentFile))
            .isInstanceOf(FileProcessingException.class)
            .hasMessageContaining("Failed to process file")
            .hasMessageContaining(nonExistentFile)
            .hasCauseInstanceOf(IOException.class);
    }

    @Test
    @DisplayName("Should verify exception is not thrown for valid input")
    void divide_withValidInput_doesNotThrowException() {
        // Given
        double dividend = 10.0;
        double divisor = 2.0;

        // When & Then
        assertThat(calculator.divide(dividend, divisor))
            .isEqualTo(5.0);
    }
}

// Test for graceful degradation
class FileManagerTest {

    @Test
    @DisplayName("Should return empty Optional when file read fails")
    void readFileContent_withNonExistentFile_returnsEmptyOptional() {
        // Given
        FileManager fileManager = new FileManager();
        String nonExistentFile = "non-existent.txt";

        // When
        Optional<String> result = fileManager.readFileContent(nonExistentFile);

        // Then
        assertThat(result).isEmpty();
        // Verify that exception was logged (would need log capture in real test)
    }
}
```

**Bad example:**

```java
// AVOID: Poor exception testing practices
class CalculatorTestBad {

    @Test
    void testDivision() {
        Calculator calculator = new Calculator();

        try {
            calculator.divide(10, 0);
            fail("Should have thrown exception"); // JUnit 4 style
        } catch (Exception e) {
            // Too generic - doesn't verify exception type or message
            assertTrue(e.getMessage().contains("zero"));
        }
    }

    @Test
    void testValidation() {
        Calculator calculator = new Calculator();

        // BAD: Not testing exception scenarios at all
        assertThat(calculator.processPositiveNumber(5)).isEqualTo(5);
        // Missing: What happens with negative numbers?
    }

    @Test
    void testFileProcessing() {
        // BAD: No exception testing for file operations
        FileProcessor processor = new FileProcessor();
        // Only testing happy path, ignoring error conditions
    }
}
```


### Example 13: Logging Policy: Structured, De-duplicated Logging

Title: Log once at boundaries with correlation IDs and error codes
Description: Centralize logging at application boundaries (e.g., controllers, message consumers, batch drivers). Lower layers should attach context and rethrow without logging to avoid duplicate log entries. Use structured logging fields like correlationId, errorCode, and userId.

**Good example:**

```java
// GOOD: Log once at the boundary with structured context
public class OrdersController {
    private static final Logger logger = LoggerFactory.getLogger(OrdersController.class);

    public Response createOrder(CreateOrderRequest request, String correlationId) {
        try {
            Order order = orderService.create(request, correlationId);
            return Response.created(order.getId());
        } catch (OrderValidationException e) {
            logger.info("order.create.validation_failed correlationId={} errorCode={}", correlationId, e.getErrorCode(), e);
            return Response.badRequest(problemFrom(e, correlationId));
        } catch (OrderSystemException e) {
            logger.error("order.create.system_error correlationId={} errorCode={}", correlationId, e.getErrorCode(), e);
            return Response.serverError(problemFrom(e, correlationId));
        }
    }
}

// Service layer: enrich and rethrow without logging
public class OrderService {
    public Order create(CreateOrderRequest request, String correlationId) throws OrderValidationException, OrderSystemException {
        try {
            validate(request);
            return repository.save(toOrder(request));
        } catch (DataIntegrityViolationException e) {
            throw new OrderValidationException("Duplicate order", ErrorCode.DUPLICATE, e).withCorrelationId(correlationId);
        } catch (SQLException e) {
            throw new OrderSystemException("Database failure", ErrorCode.SYSTEM_ERROR, e).withCorrelationId(correlationId);
        }
    }
}
```

**Bad example:**

```java
// AVOID: Duplicate logging across layers (log-and-throw)
public class NoisyService {
    private static final Logger logger = LoggerFactory.getLogger(NoisyService.class);

    public void doWork() {
        try {
            repository.save(...);
        } catch (Exception e) {
            logger.error("save failed", e); // First log
            throw new ServiceException("save failed", e);
        }
    }
}

public class NoisyController {
    private static final Logger logger = LoggerFactory.getLogger(NoisyController.class);
    public Response handle() {
        try {
            service.doWork();
            return Response.ok();
        } catch (ServiceException e) {
            logger.error("save failed", e); // Second log - duplicates
            return Response.serverError();
        }
    }
}
```

### Example 14: Exception Translation at API Boundaries

Title: Use centralized handlers to map domain errors to responses
Description: Translate internal exceptions into transport-appropriate error responses using centralized handlers. Keep domain exceptions expressive and map them to HTTP/problem-details (or messaging error contracts) at the boundary.

**Good example:**

```java
// GOOD: Centralized translation to ProblemDetails
public final class ProblemDetails {
    public final String type; // URI identifying error type
    public final String title;
    public final int status;
    public final String detail;
    public final String correlationId;
    public ProblemDetails(String type, String title, int status, String detail, String correlationId) {
        this.type = type; this.title = title; this.status = status; this.detail = detail; this.correlationId = correlationId;
    }
}

public class ApiErrorHandler {
    public Response toResponse(Throwable t, String correlationId) {
        if (t instanceof UserNotFoundException e) {
            return Response.status(404).body(new ProblemDetails(
                "urn:problem:user-not-found", "User not found", 404, e.getMessage(), correlationId));
        }
        if (t instanceof UserValidationException e) {
            return Response.status(400).body(new ProblemDetails(
                "urn:problem:validation", "Validation failed", 400, e.getMessage(), correlationId));
        }
        return Response.status(500).body(new ProblemDetails(
            "urn:problem:internal", "Internal Server Error", 500, "Unexpected error", correlationId));
    }
}
```

**Bad example:**

```java
// AVOID: Ad-hoc translation scattered across controllers
public class UsersController {
    public Response get(String id) {
        try {
            return Response.ok(service.get(id));
        } catch (Exception e) { // Too generic and repeated everywhere
            return Response.status(500).body(e.getMessage()); // Leaks internals
        }
    }
}
```

### Example 15: Retry with Backoff Only for Idempotent Operations

Title: Bounded retries, interruption-aware, transient-only
Description: Apply retries only to operations that are safe to repeat. Use bounded attempts, backoff, and transient error filtering. Preserve interruption and stop on non-transient errors.

**Good example:**

```java
// GOOD: Interruption-aware retry with backoff for idempotent fetch
public class RetryingClient {
    private static final Logger logger = LoggerFactory.getLogger(RetryingClient.class);

    public Response fetch(String resourceId) throws ClientException, InterruptedException {
        int maxAttempts = 3;
        long backoffMs = 200;
        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                return httpClient.get(resourceId); // Safe, idempotent
            } catch (IOException e) {
                if (attempt == maxAttempts || !isTransient(e)) {
                    throw new ClientException("Fetch failed after " + attempt + " attempts", e);
                }
                logger.warn("Transient failure (attempt {}), backing off {}ms", attempt, backoffMs);
                try { Thread.sleep(backoffMs); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw ie; }
                backoffMs *= 2;
            }
        }
        throw new ClientException("Unreachable code");
    }

    private boolean isTransient(IOException e) { return e instanceof java.net.SocketTimeoutException; }
}
```

**Bad example:**

```java
// AVOID: Blind retries on non-idempotent operations, swallowing interrupts
public class RiskyClient {
    public String createOrder(String body) {
        for (int i = 0; i < 10; i++) {
            try {
                return http.post("/orders", body); // Not idempotent
            } catch (Exception e) {
                // Swallow interruption and keep retrying
                try { Thread.sleep(100); } catch (InterruptedException ignored) {}
            }
        }
        throw new RuntimeException("Failed");
    }
}
```

### Example 16: Timeouts, Deadlines and Cancellation

Title: Propagate deadline exceeded and cancel ongoing work
Description: Enforce time limits for blocking calls and asynchronous operations. On timeout, cancel the work, restore interrupted status if applicable, and translate to a domain-specific timeout error.

**Good example:**

```java
// GOOD: Enforce deadline with cancellation
public class DeadlineService {
    private final ExecutorService executor = Executors.newCachedThreadPool();

    public Result computeWithDeadline(Callable<Result> task, Duration timeout) throws ProcessingException, InterruptedException {
        Future<Result> future = executor.submit(task);
        try {
            return future.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            future.cancel(true); // interrupt if running
            throw new ProcessingException("Deadline exceeded", e);
        } catch (ExecutionException e) {
            throw new ProcessingException("Task failed", e.getCause());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw e;
        }
    }
}
```

**Bad example:**

```java
// AVOID: No timeout, no cancellation, blocks indefinitely
public class SlowService {
    public Result compute() {
        try {
            return longBlockingCall(); // Could hang forever
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
```

### Example 17: Preserve Secondary Failures with Suppressed Exceptions

Title: Use addSuppressed when cleanup also fails
Description: When manual cleanup fails after a primary exception, attach the cleanup exception using `Throwable#addSuppressed` before rethrowing to retain both diagnostics. Note: try-with-resources does this automatically.

**Good example:**

```java
// GOOD: Keep both primary and cleanup failures
public void copy(Path src, Path dst) throws FileOperationException {
    FileChannel in = null, out = null;
    try {
        in = FileChannel.open(src, StandardOpenOption.READ);
        out = FileChannel.open(dst, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        in.transferTo(0, in.size(), out);
    } catch (IOException primary) {
        IOException cleanupError = null;
        try { if (in != null) in.close(); } catch (IOException e) { cleanupError = e; }
        try { if (out != null) out.close(); } catch (IOException e) { if (cleanupError != null) primary.addSuppressed(cleanupError); cleanupError = e; }
        if (cleanupError != null) primary.addSuppressed(cleanupError);
        throw new FileOperationException("Copy failed", primary);
    }
}
```

**Bad example:**

```java
// AVOID: Losing cleanup failure
public void write(Path dst) throws Exception {
    OutputStream out = null;
    try {
        out = Files.newOutputStream(dst);
        out.write(new byte[]{1});
    } catch (IOException e) {
        try { if (out != null) out.close(); } catch (IOException ignored) {}
        throw e; // Cleanup error lost
    }
}
```

### Example 18: Do Not Catch Throwable or Error

Title: Catch specific exceptions; let fatal errors propagate
Description: Catching `Throwable` or `Error` can mask fatal conditions (e.g., `OutOfMemoryError`). Restrict catch blocks to expected, recoverable exceptions.

**Good example:**

```java
// GOOD: Catch only expected exceptions
try {
    persist(entity);
} catch (SQLException e) {
    throw new RepositoryException("Persist failed", e);
}
```

**Bad example:**

```java
// AVOID: Catching Throwable masks fatal errors
try {
    run();
} catch (Throwable t) { // Too broad
    log.error("failure", t);
}
```


### Example 19: Exception Handling in Lambda Expressions and Streams

Title: Properly manage exceptions in functional constructs
Description: In functional programming with lambdas and streams, wrap throwing operations in try-catch or use checked-exception wrappers to maintain proper error handling without losing functional style.

**Good example:**

```java
// GOOD: Proper exception handling in streams
import java.util.List;
import java.util.stream.Collectors;

public class LambdaProcessor {
    public List<Result> process(List<Input> inputs) {
        return inputs.stream()
            .map(input -> {
                try {
                    return processSingle(input);
                } catch (ProcessingException e) {
                    logger.warn("Failed to process input: {}", input, e);
                    return Result.failure(input, e.getMessage());
                }
            })
            .collect(Collectors.toList());
    }

    private Result processSingle(Input input) throws ProcessingException {
        // Processing that may throw
        if (input == null) {
            throw new ProcessingException("Null input");
        }
        return Result.success(input);
    }
}
```

**Bad example:**

```java
// AVOID: Unhandled exceptions in lambdas
public class BadLambdaProcessor {
    public List<Result> process(List<Input> inputs) {
        return inputs.stream()
            .map(this::processSingle) // Throws unchecked, breaks stream
            .collect(Collectors.toList());
    }

    private Result processSingle(Input input) {
        if (input == null) {
            throw new RuntimeException("Null input"); // Bad: unchecked in lambda
        }
        return Result.success(input);
    }
}
```

### Example 20: Exception Handling in Constructors

Title: Properly handle initialization failures
Description: In constructors, validate parameters and throw exceptions for invalid states to prevent creation of invalid objects. Use factory methods for complex initialization that may fail.

**Good example:**

```java
// GOOD: Validation in constructor with factory method
public class User {
    private final String name;
    private final int age;

    private User(String name, int age) {
        Objects.requireNonNull(name, "Name cannot be null");
        if (name.trim().isEmpty()) {
            throw new IllegalArgumentException("Name cannot be empty");
        }
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        this.name = name.trim();
        this.age = age;
    }

    public static User create(String name, int age) {
        return new User(name, age);
    }
}
```

**Bad example:**

```java
// AVOID: No validation in constructor, creates invalid objects
public class BadUser {
    private String name;
    private int age;

    public BadUser(String name, int age) {
        this.name = name; // Could be null or empty
        this.age = age;   // Could be negative
    }
}
```


## Output Format

- **ANALYZE** Java code to identify specific exception handling issues and categorize them by severity (CRITICAL, HIGH, MEDIUM, LOW) and exception handling area (validation, resource management, security, thread safety, documentation, exception design)
- **CATEGORIZE** exception handling improvements found: Input Validation Issues (missing validation vs comprehensive parameter checking, inadequate sanitization vs proper input validation), Resource Management Problems (missing try-with-resources vs automatic resource management, resource leaks vs proper cleanup), Security Vulnerabilities (information disclosure vs secure error messages, sensitive data exposure vs protected exception handling), Thread Safety Problems (improper InterruptedException handling vs correct interruption patterns, concurrent access issues vs thread-safe exception handling), Exception Design Flaws (generic exceptions vs specific exception types, poor hierarchy design vs well-structured exception hierarchies), and Documentation Deficiencies (missing @throws tags vs comprehensive documentation, unclear exception descriptions vs detailed error information)
- **APPLY** exception handling best practices directly by implementing the most appropriate improvements for each identified issue: Implement comprehensive input validation with early parameter checking and proper sanitization, establish automatic resource management using try-with-resources patterns, secure exception handling through generic error messages and protected logging, implement proper thread safety with correct InterruptedException handling, design specific exception hierarchies with meaningful exception types, and provide comprehensive exception documentation with detailed @throws annotations
- **IMPLEMENT** comprehensive exception handling refactoring using proven patterns: Establish robust input validation with null checks, range validation, and format validation, implement automatic resource management with try-with-resources for all closeable resources, apply security-focused exception handling with sanitized error messages and secure logging, design proper exception hierarchies with domain-specific exceptions, implement thread-safe exception handling with proper interruption support, and integrate comprehensive exception documentation with detailed error descriptions and recovery guidance
- **REFACTOR** code systematically following the exception handling improvement roadmap: First implement critical input validation to prevent invalid state and security vulnerabilities, then establish automatic resource management to prevent resource leaks, apply security measures to protect sensitive information in exceptions, implement proper thread safety in exception handling, design and apply well-structured exception hierarchies, and complete comprehensive exception documentation for maintainability and debugging support
- **EXPLAIN** the applied exception handling improvements and their benefits: Reliability enhancements through comprehensive input validation and resource management, security improvements via protected error messages and secure exception handling, maintainability gains from well-structured exception hierarchies and comprehensive documentation, thread safety improvements through proper interruption handling, and debugging capabilities enhancement through detailed exception information and recovery guidance
- **VALIDATE** that all applied exception handling refactoring compiles successfully, maintains existing functionality, improves error handling robustness, eliminates security vulnerabilities, and achieves the intended reliability and maintainability improvements through comprehensive testing and verification


## Safeguards

- **BLOCKING SAFETY CHECK**: ALWAYS run `./mvnw compile` before ANY exception handling recommendations to ensure project stability
- **CRITICAL VALIDATION**: Execute `./mvnw clean verify` to ensure all tests pass after each exception handling improvement
- **MANDATORY VERIFICATION**: Confirm all existing functionality remains intact through comprehensive test execution
- **ROLLBACK REQUIREMENT**: Ensure all exception handling changes can be easily reverted using version control checkpoints
- **INCREMENTAL SAFETY**: Apply exception handling improvements incrementally, validating after each modification to isolate potential issues
- **SECURITY VALIDATION**: Verify that exception handling improvements don't introduce information disclosure vulnerabilities or expose sensitive system details
- **THREAD SAFETY VERIFICATION**: Ensure that concurrent exception handling changes don't introduce race conditions or deadlocks
- **BACKWARD COMPATIBILITY**: Maintain API compatibility when changing exception types or adding new exception handling patterns
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 319kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 319kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 319kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 319kUpdated Claude CodeCodexVerifiedInstall