How can error handling be improved in the provided PHP script to provide more useful feedback to the user?

The issue with the provided PHP script is that it lacks specific error messages for different types of errors that may occur during file upload. To improve error handling and provide more useful feedback to the user, we can use try-catch blocks to catch specific exceptions and display appropriate error messages.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload error. Please try again.');
        }

        $file_name = $_FILES['file']['name'];
        $file_tmp = $_FILES['file']['tmp_name'];

        if (!move_uploaded_file($file_tmp, "uploads/$file_name")) {
            throw new Exception('Failed to move uploaded file. Please try again.');
        }

        echo 'File uploaded successfully.';
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
    }
}
?>