This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

PHP Exceptions

Throwing an Exception

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

echo divide(5, 0);
?>

The above code causes a fatal error that terminates the script and prevents the rest of the page from loading. The only error message is in the web server logs. It looks something like this, if the server is running a unix style server:

[Wed Sep 18 16:18:22.974257 2024] [php7:error] [pid 5468] [client ::1:55908] 
PHP Fatal error:  Uncaught Exception: Division by zero in /srv/www/htdocs/W3School-WebDevelopment/php/PHPExceptions.php:41\n
Stack trace:\n#0 /srv/www/htdocs/W3School-WebDevelopment/php/PHPExceptions.php(46): 
divide()\n#1 {main}\n  thrown in /srv/www/htdocs/W3School-WebDevelopment/php/PHPExceptions.php on line 41, 
referer: http://localhost/W3School-WebDevelopment/php/6-13PHPExceptions.php