Avatar of elepil
elepil
 asked on

catch block in a try/catch not working

My code sample is simply trying to connect to a database:

try {
    $db = new mysqli('localhost', 'username', 'password', 'database');
    if ($db->connect_error) {
        $error = $db->connect_error;
        echo "From try: " . $error . "<br/>";
    } else {
        echo "From try: Success!" . "<br/>";
    }
} catch(Exception $e) {
    $error->$e->getMessage();
    echo "From catch: " . $error . "<br/>";
}

Open in new window


I'd intentionally put in the wrong user name or password, and it bombs out as expected. What I don't understand is why the catch block is not catching the error because it's the statements in the try block that's displaying the error. Can someone explain to me why this is the case?

Thanks.
Network Analysis

Avatar of undefined
Last Comment
elepil

8/22/2022 - Mon
Mark Bullock

The database code is not throwing an exception. It is returning an error which you are testing in the if statement.
elepil

ASKER
To Mark Bullock. Thanks for responding.

That's what I suspected, but the PHP page actually reports the error with its typical orange table block. It is common for database-related function to throw exceptions, as that is what I've become accustomed to in Java. If it isn't throwing exceptions on a critical function as an incorrect username and password to the database, when would it throw exceptions?
ASKER CERTIFIED SOLUTION
Mark Bullock

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
elepil

ASKER
That was what I needed, thanks!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23