codegurukool.com · Free coding tutorials & online compiler

Home › PHP Tutorial › PHP exceptions

PHP exceptions

Handle errors safely with try and catch.

throw raises an exception, catch handles it, and finally always runs, even after an error.

Example code

<?php
function div($a, $b) {
  if ($b === 0) throw new Exception("Cannot divide by zero");
  return $a / $b;
}
try {
  echo div(10, 2) . PHP_EOL;
  echo div(1, 0);
} catch (Exception $e) {
  echo "Error: " . $e->getMessage();
} finally {
  echo PHP_EOL . "Done";
}
?>

Run this code in the online editor

← PHP JSONPHP classes, objects and constructors →