How can PHP developers effectively handle error messages and exceptions when writing data to a file in PHP?

When writing data to a file in PHP, developers can effectively handle error messages and exceptions by using try-catch blocks to catch any potential errors that may occur during the file writing process. By using try-catch blocks, developers can gracefully handle any exceptions that may arise, such as file permission issues or disk space limitations, and provide appropriate error messages to the user.

try {
    $file = fopen("data.txt", "w");
    if ($file === false) {
        throw new Exception("Unable to open file for writing");
    }
    
    fwrite($file, "Hello, world!");
    
    fclose($file);
    
    echo "Data written to file successfully.";
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}