Skip to content

Ch: 003 Error handling

heikijapan edited this page Oct 6, 2026 · 4 revisions

There are several ways of error handling in PHP. TRY & CATCH block is the most used one.

  • It can cover large code blocks and be even wrapped or span over IF blocks.
  • Instead of one big block, it would be better to have smaller blocks in that way it will be easier to define the cause of an error.
  • It is smart to have one try & catch protect PDO connection block and then one individual try & catch for every CRUD operation.
  • To define your own error blocks and messages Throwable is used.
try {
$pdo = new PDO('mysql info etc');
$stmt = $pdo->prepare('SELECT * FROM `my_database_table` WHERE `id` < 5 ASC');
$stmt->execute()

} catch (PDOException $e) {

// This logs errors into server log file, DIR can be found using phpinfo()
// If you want to use your own log file, then use log_errors();
error_log($e->getMessage());

$msg = 'Something went wrong! Cannot connect to MySQL database`;

}

Clone this wiki locally