PHP Exceptions

PHP Exceptions

An Exception is an object that describes an error or unexpected behavior in a PHP script. Exceptions are thrown by many PHP functions and classes, and you can even throw your own!

Handling exceptions prevents your script from completely crashing and showing an ugly fatal error to the user.


The try...catch Statement

Exceptions are handled using try...catch blocks.

Exception Example

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    // Manually trigger an exception!
    throw new Exception("Division by zero is mathematically impossible!");
  }
  return $dividend / $divisor;
}

try { // We try to execute code that might fail echo divide(5, 0); echo "This line will never execute because an exception was thrown."; } catch(Exception $e) { // We catch the error object and print its message echo "Error Caught: " . $e->getMessage(); } ?>


The finally Block

The try...catch statement can optionally include a finally block.

Code inside the finally block will always execute, regardless of whether an exception was thrown and caught or not. This is perfect for cleaning up resources, like closing a database connection or a file!

try {
  // Code that might throw an exception
} catch(Exception $e) {
  // Code to handle the exception
} finally {
  // Code that ALWAYS runs
}

Exercise

?

Which keyword is used to manually generate and send an exception object in PHP?