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).