openfrog
openfrog

Reputation: 40735

How to catch this nested exceptions?

Example: I use a PDO method that throws an exception. But inside the try block, I also throw an own Exception if something else goes wrong. Now I want to handle the PDOException and my own Exception separately. How could I separate this to make it work?

   public function prepare(string $sql, array $params) {
    try {
        $prepared = $this->dbh->prepare($sql); // may throw PDOException
        $i = 1;
        foreach ($params as $param) {
        $ok = $prepared->bindParam($i, $param);
        if (!$ok) {
            throw new Exception("Unable to bind parameter (" . $param . ") to prepared statement: " . $sql);
        }
        $i++;
        }
    } catch (PDOException $e) {
        throw new Exception("DB:prepare(): Could not prepare statement. " . $e->getMessage());
    }
    return $prepared;
   }

Please note that I have a global error handler that takes care of logging any exception to a file. That's why I throw my own exceptions instead of writing directly to a log file (that way, I get also the backtrace).

Upvotes: 1

Views: 3054

Answers (2)

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

You can use several catch blocks, like this :

try {
    // ...
} catch (PDOException $e) {
    // Handle the PDOException, with some specific code
} catch (Exception $e) {
    // Handle any other kind of Exception 
    // that has not already been catched by 
    // one of the previous(es) catch block
}

But note you have to put the "most specific" exception type first -- which means Exception has to be the last one.


Here are a couple of articles / blog-posts that might interest you, about exceptions and PHP :

Upvotes: 7

raphaelr
raphaelr

Reputation: 67

multiple catches? Or catch only an Exception and check it's type.

Upvotes: 1

Related Questions