How can error handling be improved in the provided PHP code for downloading files from a server?

The issue with the provided PHP code for downloading files from a server is that it lacks proper error handling, which can lead to unexpected behavior or security vulnerabilities. To improve error handling, we can use try-catch blocks to catch any exceptions that may occur during the file download process and handle them appropriately.

<?php
$url = 'http://example.com/file.zip';
$destination = '/path/to/save/file.zip';

try {
    $file = file_get_contents($url);
    if ($file === false) {
        throw new Exception('Failed to download file');
    }

    $saved = file_put_contents($destination, $file);
    if ($saved === false) {
        throw new Exception('Failed to save file');
    }

    echo 'File downloaded successfully.';
} catch (Exception $e) {
    echo 'An error occurred: ' . $e->getMessage();
}
?>