• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 86
  • Last Modified:

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.
0
elepil
Asked:
elepil
  • 2
  • 2
1 Solution
 
Mark BullockQA Engineer IIICommented:
The database code is not throwing an exception. It is returning an error which you are testing in the if statement.
0
 
elepilAuthor Commented:
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?
0
 
Mark BullockQA Engineer IIICommented:
You can enable exceptions using:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Open in new window

0
 
elepilAuthor Commented:
That was what I needed, thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now