Can you provide specific examples of when to use trigger_error and when to use Exception in PHP code?
When to use trigger_error: Use trigger_error when you want to generate a user-level error message and continue the script execution. This can be useful for non-critical errors that do not require halting the script. When to use Exception: Use Exception when you want to throw an exception that can be caught and handled by the calling code. Exceptions are typically used for critical errors that require immediate attention and may need to stop the script execution. Example of using trigger_error:
// Check if a file exists and trigger an error if it doesn't
$file = 'example.txt';
if (!file_exists($file)) {
trigger_error('File does not exist: ' . $file, E_USER_ERROR);
}
```
Example of using Exception:
```php
// Check if a user is logged in and throw an exception if they are not
function checkLoggedIn() {
if (!$loggedIn) {
throw new Exception('User is not logged in');
}
}
try {
checkLoggedIn();
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}