How can you improve the code provided to handle exceptions when accessing URLs?
The code needs to handle exceptions that may occur when accessing URLs, such as network errors or invalid URLs. This can be achieved by using try-catch blocks to catch exceptions and handle them gracefully. By implementing proper exception handling, the code can provide better error messages and prevent the script from crashing unexpectedly.
<?php
$url = 'https://www.example.com';
try {
$content = file_get_contents($url);
if ($content === false) {
throw new Exception('Failed to retrieve content from URL');
}
echo $content;
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>