w3resource

PHP Database Connection: Exception handling

PHP Exception Handling: Exercise-8 with Solution

Write a PHP program that simulates a database connection and throws an exception if it fails.

Sample Solution:

PHP Code :

<?php
class DatabaseConnectionException extends Exception {
    public function __construct($message, $code = 0, Throwable $previous = null) {
        parent::__construct($message, $code, $previous);
    }

    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }
}

function connectToDatabase($host, $username, $password, $database) {
    // Simulate a database connection attempt
    $success = false;

    // Check if the connection was successful
    if (!$success) {
        throw new DatabaseConnectionException("Failed to connect to the database.");
    }

    // Return the database connection object if successful
    return $databaseConnection;
}

try {
    $host = "localhost";
    $username = "root";
    $password = "password";
    $database = "database";

    $databaseConnection = connectToDatabase($host, $username, $password, $database);
    echo "Database connection successful!";
} catch (DatabaseConnectionException $e) {
    echo "An error occurred: " . $e->getMessage();
}
?>

Sample Output:

An error occurred: Failed to connect to the database.

Explanation:

In the above exercise, we define a custom exception class DatabaseConnectionException that extends the base Exception class. The custom exception class has a constructor that calls the parent constructor and overrides the __toString() method. This is to provide a custom string representation of the exception.

We have a function connectToDatabase() that attempts to connect to a database. In this example, we simulate a database connection attempt that always fails by setting $success to false. If the connection fails, we throw an instance of the DatabaseConnectionException class with the message "Failed to connect to the database."

In the main code, we call the connectToDatabase() function with the appropriate parameters for the database connection. If the connection fails, it throws DatabaseConnectionException, which is caught in the catch block. We display the error message using $e->getMessage().

Flowchart:

Flowchart: Exception handling
Flowchart: Exception handling

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Multiple catch blocks.
Next: PHP exception handling with the finally block.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/exception-handling/php-exception-handling-exercise-8.php