What best practices should be followed when handling error messages and result validation in PHP scripts?

When handling error messages and result validation in PHP scripts, it is important to provide clear and informative error messages to users to help them understand what went wrong. Additionally, always validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Use try-catch blocks to catch exceptions and handle errors gracefully.

try {
    // Perform validation on user input
    if (!isset($_POST['username'])) {
        throw new Exception('Username is required');
    }

    // Process the form submission
    // ...

    // Display success message
    echo 'Form submitted successfully';
} catch (Exception $e) {
    // Display error message
    echo 'Error: ' . $e->getMessage();
}