How can error handling be implemented effectively in PHP scripts that execute system commands, like shutdown, to address issues such as access denied errors?

When executing system commands in PHP scripts, such as shutdown, access denied errors may occur due to insufficient permissions. To address this, error handling can be implemented by using try-catch blocks to catch exceptions and handle them gracefully. By checking for specific error codes, such as permission denied errors, appropriate actions can be taken, such as displaying a user-friendly message or logging the error for further investigation.

try {
    // Attempt to execute system command
    exec('shutdown -h now');
} catch (Exception $e) {
    // Check for specific error code (permission denied)
    if ($e->getCode() == 126) {
        // Handle access denied error
        echo "Error: Permission denied to execute system command.";
    } else {
        // Handle other errors
        echo "An error occurred: " . $e->getMessage();
    }
}