What are some common strategies for handling errors and exceptions when searching through directories and files in PHP?

When searching through directories and files in PHP, it is important to handle errors and exceptions that may occur, such as file not found or permission denied. One common strategy is to use try-catch blocks to catch exceptions and handle them gracefully, displaying an appropriate error message to the user.

try {
    // Attempt to open a directory
    $dir = opendir('/path/to/directory');

    if (!$dir) {
        throw new Exception('Unable to open directory');
    }

    // Process files in the directory
    while (($file = readdir($dir)) !== false) {
        // Do something with the file
    }

    closedir($dir);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}