I'm working on a Java application that involves file I/O, and I'm dealing with checked exceptions, specifically FileNotFoundException when attempting to read a file. I want to handle this exception gracefully in my code.

Here's a simplified version of what I'm trying to do:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileProcessor {
    public static void main(String[] args) {
        String fileName = "sample.txt";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = reader.readLine()) != null) {
        } catch (IOException e) {
            System.err.println("An error occurred while reading the file: " + e.getMessage());

In this code, I'm attempting to read the contents of a file named "sample.txt." If the file doesn't exist or there's an I/O error, a FileNotFoundException or an IOException might occur.

I want to improve the exception handling in my code to provide more meaningful error messages and possibly take different actions based on the exception type. Could you provide a concise Java code example demonstrating how to handle these exceptions effectively while keeping the code clean and readable? Thank you for your assistance!