What are the best practices for handling MySQL connection errors in PHP?

When handling MySQL connection errors in PHP, it is important to use try-catch blocks to catch exceptions thrown by the connection process. Additionally, it is recommended to use the mysqli_connect_errno() and mysqli_connect_error() functions to retrieve specific error information. Finally, it is good practice to log or display the error message to aid in troubleshooting.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
} catch (Exception $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>